Написать класс исключений, возникающих при работе со списком
16.02.2012, 22:07. Показов 3806. Ответов 1
Задача звучит так: (осталось написать лишь класс исключений, выделено жирным)
Как это сделать? С чего начать? Буду благодарна любой помощи! Классы списков приложены ниже, если понадобится.
Задача направлена на создание обобщенных классов, описывающих различные структуры данных, с применением итераторов, делегатов и исключений. Все классы должны быть описаны в каком-либо пространстве имен и, возможно, его подпространствах. Использовать встроенную функциональность коллекций в .NET FCL запрещено.
Разработать библиотеку обобщенных классов для работы со списками данных. В структуру классов входят:
1. Библиотека для работы со списками
IList<T>:IEnumerable<T> - базовый интерфейс для всех списков
методы:
- int Add(T value)
- void Clear()
- bool Contains(T value)
- int IndexOf(T value)
- int IndexOf(T value)
- void Insert(int index, T value)
- void Remove (T value)
- void RemoveAt(int index)
- IList<T> subList(int fromIndex, int toIndex)
свойства:
- int Count;
- T this[int index]
* ListException - класс, описывающий исключения, которые могут происходить в ходе работы со списком (также можно написать ряд наследников)
* ArrayList<T>:IList<T> - класс списка на основе массива
* LinkedList<T>:IList<T> - класс списка на основе связанного списка
| C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace task_3
{
public interface IList<T> : IEnumerable<T>
{
T this[int index] { get; set; }
int count { get; set; }
int Add(T value);
void Clear();
bool Contains(T value);
int IndexOf(T value);
void Insert(int index, T value);
bool Remove(T value);
void RemoveAt(int index);
IList<T> subList(int FromIndex, int ToIndex);
}
} |
|
| C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace task_3
{
public class DoublyLinkedListNode<T>
{
DoublyLinkedList<T> m_owner;
DoublyLinkedListNode<T> m_prev; // предыдущее звено
DoublyLinkedListNode<T> m_next; // следущее звено
T m_data;
public DoublyLinkedListNode(T data) // создание звена со значением data
{
m_data = data;
m_owner = null;
}
internal DoublyLinkedListNode(DoublyLinkedList<T> owner, T data)
{
m_data = data;
m_owner = owner;
}
public DoublyLinkedListNode<T> Next // поле - следующее звено
{
get { return m_next; }
internal set { m_next = value; }
}
internal DoublyLinkedList<T> Owner // поле - владелец
{
get { return m_owner; }
set { m_owner = value; }
}
public DoublyLinkedListNode<T> Previous // поле - предыдущее звено
{
get { return m_prev; }
internal set { m_prev = value; }
}
public T Data // поле - данные
{
get { return m_data; }
internal set { m_data = value; }
}
}
} |
|
| C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
// Класс списка на основе двусвязного списка.
namespace task_3
{
public class DoublyLinkedList<T> : task_3.IList<T>, IEnumerable<T>
{
// поля
public int count { get; set; }
private DoublyLinkedListNode<T> m_head;
private DoublyLinkedListNode<T> m_tail;
public DoublyLinkedListNode<T> Head // голова списка
{
get { return m_head; }
private set { m_head = value; }
}
public DoublyLinkedListNode<T> Tail // хвост списка
{
get { return m_tail; }
private set { m_tail = value; }
}
public bool IsEmpty // проверка на пустоту
{
get { return count <= 0; }
}
//---------------------------------------------------------------------------------------------
public DoublyLinkedList() // пустой конструктор
{ }
//---------------------------------------------------------------------------------------------
public DoublyLinkedListNode<T> AddLast(T value) // то же, что и ADD, добавление в конец
{
DoublyLinkedListNode<T> newNode = new DoublyLinkedListNode<T>(this, value);
if (IsEmpty)
{
m_head = newNode;
m_tail = newNode;
}
else
{
newNode.Previous = m_tail;
m_tail.Next = newNode;
m_tail = newNode;
}
++count;
return newNode;
}
//---------------------------------------------------------------------------------------------
public DoublyLinkedList(IEnumerable<T> collection) // конструктор со значениями
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
foreach (T local in collection)
{
this.AddLast(local);
}
}
//---------------------------------------------------------------------------------------------
public DoublyLinkedListNode<T> Find(T data)
{
if (IsEmpty)
{
return null;
}
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
// обходим список с головы до хвоста
for (DoublyLinkedListNode<T> curr = Head; curr != null; curr = curr.Next)
{
// если звено содержит нужные данные, возвращаем его в качестве результата
if (comparer.Equals(curr.Data, data))
{
return curr;
}
}
return null;
}
//--------------------------------------------------------------------------------------------- добавления
public DoublyLinkedListNode<T> AddToBeginning(T value) // возвращает ссылку на новодобавленный объект
{
DoublyLinkedListNode<T> newNode = new DoublyLinkedListNode<T>(this, value);
if (IsEmpty)
{
m_head = newNode;
m_tail = newNode;
}
else
{
newNode.Next = m_head;
m_head.Previous = newNode;
m_head = newNode;
}
++count;
return newNode;
}
//---------------------------------------------------------------------------------------------
public void AddAfter(DoublyLinkedListNode<T> node, DoublyLinkedListNode<T> newNode) // добавляет ЗА звеном, без значения
{
if (node == null)
{
throw new ArgumentNullException("node");
}
if (newNode == null)
{
throw new ArgumentNullException("newNode");
}
if (node.Owner != this)
{
throw new InvalidOperationException("node is not owned by this list");
}
if (newNode.Owner != this)
{
throw new InvalidOperationException("newNode is not owned by this list");
}
if (node == m_tail)
{
m_tail = newNode;
}
if (node.Next != null)
{
node.Next.Previous = newNode;
}
newNode.Next = node.Next;
newNode.Previous = node;
node.Next = newNode;
++count;
}
//---------------------------------------------------------------------------------------------
public DoublyLinkedListNode<T> AddAfter(DoublyLinkedListNode<T> node, T value) // возращает звено, за которым было произведено добавление
{
DoublyLinkedListNode<T> newNode = new DoublyLinkedListNode<T>(this, value);
AddAfter(node, newNode);
return newNode;
}
//---------------------------------------------------------------------------------------------
public void AddBefore(DoublyLinkedListNode<T> node, DoublyLinkedListNode<T> newNode)
{
if (node == null)
{
throw new ArgumentNullException("node");
}
if (newNode == null)
{
throw new ArgumentNullException("newNode");
}
if (node.Owner != this)
{
throw new InvalidOperationException("node is not owned by this list");
}
if (newNode.Owner != this)
{
throw new InvalidOperationException("newNode is not owned by this list");
}
// находим предыдущее звено
if (m_head == node)
{
newNode.Next = m_head;
m_head.Previous = newNode;
m_head = newNode;
}
else
{
// вставляем новое между текущим и следующим
if (node.Previous != null)
{
node.Previous.Next = newNode;
}
newNode.Previous = node.Previous;
newNode.Next = node;
node.Previous = newNode;
}
++count;
}
//---------------------------------------------------------------------------------------------
public DoublyLinkedListNode<T> AddBefore(DoublyLinkedListNode<T> node, T value)
{
DoublyLinkedListNode<T> newNode = new DoublyLinkedListNode<T>(this, value);
AddBefore(node, newNode);
return newNode;
}
//----------------------------------------------------------------------------------------------
public bool Contains(T value) // содержит ли список данные
{
return Find(value) != null;
}
//--------------------------------------------------------------------------------------------- !!!!!!!!!!!!!!!!!
public bool Remove(T value)
{
if (IsEmpty)
{ return false; }
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
bool removed = false;
DoublyLinkedListNode<T> curr = Head;
while (curr != null)
{
// те ли данные содержатся
if (!comparer.Equals(curr.Data, value))
{
curr = curr.Next;
continue;
}
if (curr.Previous != null)
{ curr.Previous.Next = curr.Next; }
// в следующем - указатель на предыдущий
if (curr.Next != null)
{ curr.Next.Previous = curr.Previous; }
if (curr == Head)
{
// если голова, то теперь голова - это следующее
Head = curr.Next;
}
if (curr == Tail)
{
// если хвост, то теперь предыдущее - хвост
Tail = curr.Previous;
}
// сохраним чтобы потом удалить
DoublyLinkedListNode<T> tmp = curr;
// переход на следующее
curr = curr.Next;
// обнуляем указатели
tmp.Next = null;
tmp.Previous = null;
tmp.Owner = null;
//уменьшаем количество
--count;
removed = true;
break;
}
return removed;
}
//---------------------------------------------------------------------------------------------
public int Add(T value) // добавление, возвращает индекс, по которому элемент был добавлен
{
AddLast(value);
return IndexOf(value);
}
//---------------------------------------------------------------------------------------------
public void Clear()
{
DoublyLinkedListNode<T> tmp;
// пока голова не окажется пустой
for (DoublyLinkedListNode<T> node = m_head; node != null; )
{
tmp = node.Next;
// изменяем количество и голову
m_head = tmp;
if (tmp != null)
{ tmp.Previous = null; }
--count;
// удаляем содержимое
node.Next = null;
node.Previous = null;
node.Owner = null;
// к следующему
node = tmp;
}
if (count <= 0)
{
m_head = null;
m_tail = null;
}
}
//-------------------------------------- ENUMERATOR ------------------------------------------------------
public struct Enumerator: IEnumerator<T>, IEnumerator
{
private const string LinkedListName = "LinkedList";
private const string CurrentValueName = "Current";
private DoublyLinkedList<T> list;
private DoublyLinkedListNode<T> node;
private T current;
private int index;
//---------------------------------------------------------------------------------------
internal Enumerator(DoublyLinkedList<T> list)
{
this.list = list;
this.node = list.Head;
this.current = default(T);
this.index = 0;
}
//---------------------------------------------------------------------------------------
public T Current
{
get
{
return this.current;
}
}
//---------------------------------------------------------------------------------------
object IEnumerator.Current
{
get
{
if ((this.index == 0) || (this.index == (this.list.count + 1)))
{
throw new ArgumentOutOfRangeException();
}
return this.current;
}
}
//---------------------------------------------------------------------------------------
public bool MoveNext()
{
if (this.node == null)
{
this.index = this.list.count + 1;
return false;
}
this.index++;
this.current = this.node.Data;
this.node = this.node.Next;
if (this.node == this.list.Head)
{
this.node = null;
}
return true;
}
//--------------------------------------------------------------------------------------
public bool MovePrev()
{
this.index--;
this.current = this.node.Data;
this.node = this.node.Previous;
if (this.node == this.list.Tail)
{
this.node = null;
}
return true;
}
//----------------------------------------------------------------------------------------
void IEnumerator.Reset()
{
this.current = default(T);
this.node = this.list.Head;
this.index = 0;
}
//----------------------------------------------------------------------------------------
public void Dispose()
{
}
}
//------------------------------------ end ENUMERATOR --------------------------------------------- // ?
public IEnumerator<T> GetEnumerator()
{
return new Enumerator((DoublyLinkedList<T>)this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
//---------------------------------------------------------------------------------------------
// штуки с индексами
public T[] ToArray() // преобразовать список в массив
{
T[] retval = new T[count];
int index = 0;
for (DoublyLinkedListNode<T> i = Head; i != null; i = i.Next)
{
retval[index] = i.Data;
++index;
}
return retval;
}
//--------------------------------------------------------------------------------------------
public void ToList(T[] A)
{
Clear();
foreach (T s in A)
{
AddLast(s);
}
}
//----------------------------------------------------------------------------------------------
public T this[int index] // обращение по индексу
{
get
{
T[] tmp = ToArray();
return tmp[index];
}
set
{
throw new NotImplementedException(); // ????
}
}
//---------------------------------------------------------------------------------------------
public int IndexOf(T value)
{
return Array.IndexOf<T>(ToArray(), value, 0, count);
}
//---------------------------------------------------------------------------------------------
public void Insert(int index, T value) // вставить после заданного индекса
{
T[] arr = ToArray();
DoublyLinkedListNode<T> tmp = Find(arr[index]);
AddAfter(tmp, value);
}
//---------------------------------------------------------------------------------------------
public void RemoveAt(int index) // удалить звено, находящееся по определенному индексу
{
T[] arr = ToArray();
Remove(arr[index]);
}
//---------------------------------------------------------------------------------------------
public IList<T> subList(int FromIndex, int ToIndex) // создание подсписка
{
T[] buf = ToArray();
DoublyLinkedList<T> lst = new DoublyLinkedList<T>();
if ((FromIndex >= ToIndex) || (ToIndex > count)) {throw new ArgumentOutOfRangeException("wrong indexes"); }
for (int i = FromIndex; i <= ToIndex; i++)
{
lst.AddLast(buf[i]);
}
return lst;
}
//-------------------------------------------------------------------------------------------------
}
} |
|
| C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace task_3
{
public class ArrayList<T> : task_3.IList<T>, IEnumerable<T>
{
private T[] items;
private int size; // размер
private static readonly T[] emptyArray;
public T this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
//---------------------------------------------------------------------------------
public int count
{
get { return size; }
set { }
}
//----------------------------------------------------------------------------------
public ArrayList(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException();
}
this.items = new T[capacity];
}
//-----------------------------------------------------------------------------------
public ArrayList() // пустой конструктор
{
this.items = ArrayList<T>.emptyArray;
}
//---------------------------------------------------------------------------------
public int Capacity // размер массива
{
get
{ return this.items.Length; }
set
{
if (value < this.size) // value - новый размер
{
throw new ArgumentOutOfRangeException();
}
if (value != this.items.Length)
{
if (value > 0)
{
T[] destinationArray = new T[value];
if (this.size > 0) // если что-то уже есть в массиве
{
Array.Copy(this.items, 0, destinationArray, 0, this.size);
}
this.items = destinationArray;
}
else
{
this.items = ArrayList<T>.emptyArray;
}
}
}
}
//---------------------------------------------------------------------------------
private void EnsureCapacity(int min)
{
if (this.items.Length < min)
{
int num = (this.items.Length == 0) ? 4 : (this.items.Length * 2);
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}
//---------------------------------------------------------------------------------
public int Add(T value)
{
if (this.size == this.items.Length) // если заполнен уже до упора
{
this.EnsureCapacity(this.size + 1);
}
this.items[this.size++] = value;
return this.size;
}
//---------------------------------------------------------------------------------
public void Clear() // очистка массива
{
if (this.size > 0)
{
Array.Clear(this.items, 0, this.size);
this.size = 0;
}
}
//---------------------------------------------------------------------------------
public bool Contains(T value) // содержит ли список заданное значение
{
if (value == null)
{
for (int j = 0; j < this.size; j++)
{
if (this.items[j] == null)
{
return true;
}
}
return false;
}
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < this.size; i++)
{
if (comparer.Equals(this.items[i], value))
{
return true;
}
}
return false;
}
//---------------------------------------------------------------------------------
public int IndexOf(T value) // возвращает индекс искомого значения
{
return Array.IndexOf<T>(this.items, value, 0, this.size);
}
//---------------------------------------------------------------------------------
public void Insert(int index, T value)
{
if (index > this.size)
{
throw new ArgumentOutOfRangeException();
}
if (this.size == this.items.Length)
{
this.EnsureCapacity(this.size + 1);
}
if (index < this.size)
{
Array.Copy(this.items, index, this.items, index + 1, this.size - index); // сдвиг на единицу после заданного индекса
}
this.items[index] = value;
this.size++;
}
//---------------------------------------------------------------------------------
public bool Remove(T value) // удаление заданного значения
{
int index = this.IndexOf(value);
if (index >= 0)
{
this.RemoveAt(index);
return true;
}
return false;
}
//---------------------------------------------------------------------------------
public void RemoveAt(int index) // удаление по определенному индексу
{
if (index >= this.size)
{
throw new ArgumentOutOfRangeException();
}
this.size--;
if (index < this.size)
{
Array.Copy(this.items, index + 1, this.items, index, this.size - index); // сжимаем массив
}
this.items[this.size] = default(T);
}
//---------------------------------------------------------------------------------
public IList<T> subList(int FromIndex, int ToIndex)
{
ArrayList<T> res = new ArrayList<T>();
int j = 0;
for (int i = FromIndex; i <= ToIndex; i++)
{
res[j] = this[i];
j++;
}
return res;
}
//---------------------------------------------------------------------------------- ENUMERATOR
public struct Enumerator : IEnumerator<T>, IDisposable
{
private ArrayList<T> list;
private int index;
private T current;
internal Enumerator(ArrayList<T> list)
{
this.list = list;
this.index = 0;
this.current = default(T);
}
//----------------------------------------------------------------------------------
public void Dispose()
{
}
//----------------------------------------------------------------------------------
public bool MoveNext()
{
ArrayList<T> list = this.list;
if ((this.index < list.size))
{
this.current = list.items[this.index];
this.index++;
return true;
}
return this.MoveNextRare();
}
//----------------------------------------------------------------------------------
private bool MoveNextRare()
{
this.index = this.list.size + 1;
this.current = default(T);
return false;
}
//----------------------------------------------------------------------------------
public T Current
{
get
{
return this.current;
}
}
//----------------------------------------------------------------------------------
object System.Collections.IEnumerator.Current
{
get
{
if ((this.index == 0) || (this.index == (this.list.size + 1)))
{
throw new InvalidOperationException();
}
return this.Current;
}
}
//----------------------------------------------------------------------------------
void System.Collections.IEnumerator.Reset() // сброс
{
this.index = 0;
this.current = default(T);
}
}
//---------------------------------------------------------------------------------
public IEnumerator<T> GetEnumerator()
{
return new Enumerator((ArrayList<T>)this);
}
//---------------------------------------------------------------------------------
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator((ArrayList<T>)this);
}
}
//---------------------------------------------------------------------------------
} |
|
0
|