myarraylist class

Solutions on MaxInterview for myarraylist class by the best coders in the world

showing results for - "myarraylist class"
Michela
19 Sep 2016
1 
2public class MyArrayList<E> 
3{
4  private int size; // Number of elements in the list
5  private E[] data;
6  private int MAXELEMENTS = 100;
7  /** Create an empty list */
8  public MyArrayList() {
9	   data = (E[])new Object[MAXELEMENTS];// cannot create array of generics
10       size = 0; // Number of elements in the list
11  }
12  
13  public void add(int index, E e) {   
14    // Ensure the index is in the right range
15    if (index < 0 || index > size)
16      throw new IndexOutOfBoundsException
17        ("Index: " + index + ", Size: " + size); 
18    // Move the elements to the right after the specified index
19    for (int i = size - 1; i >= index; i--)
20      data[i + 1] = data[i];
21    // Insert new element to data[index]
22    data[index] = e;
23    // Increase size by 1
24    size++;
25  }
26
27  public boolean contains(Object e) {
28    for (int i = 0; i < size; i++)
29      if (e.equals(data[i])) return true;
30    return false;
31  }
32
33  public E get(int index) {
34    if (index < 0 || index >= size)
35      throw new IndexOutOfBoundsException
36        ("Index: " + index + ", Size: " + size);
37    return data[index];
38  }
39  
40  public E remove(int index) {
41	if (index < 0 || index >= size)
42      throw new IndexOutOfBoundsException
43        ("Index: " + index + ", Size: " + size);
44    E e = data[index];
45    // Shift data to the left
46    for (int j = index; j < size - 1; j++)
47      data[j] = data[j + 1];
48    data[size - 1] = null; // This element is now null
49    // Decrement size
50    size--;
51    return e;
52  }
53  
54  public void clear()
55  {
56     size = 0;
57  }
58  
59  public void filter (E low, E high)
60  {
61	  int j=0;
62	  E[] temp = (E[])new Object[MAXELEMENTS];
63	  
64	  if (getSize()== 0)
65		  return;
66	  if (((Comparable)low).compareTo(high)>0)
67		  return;
68	  
69	  for (int i = 0; i< size; i++)
70	  {
71		if ((((Comparable)data[i]).compareTo(low) >=0) &&
72		  (((Comparable)data[i]).compareTo(high) <=0))
73		{	
74			temp[j] = data[i];
75		    j++;
76		}
77	  }
78	  data = temp;
79	  size = j;
80  }
81 
82		  
83	  
84  public String toString() {
85    String result="[";
86    for (int i = 0; i < size; i++) {
87      result+= data[i];
88      if (i < size - 1) result+=", ";
89    }
90    return result.toString() + "]";
91  }
92
93  
94  public int getSize() {
95    return size;
96  }
97  
98 public boolean sortList() {
99    E hold;
100	for (int i = 0; i < size-1; i++)
101	 {
102	   for (int j = 0; j<size-1; j++)
103	    {  	 
104	     if(((Comparable)data[j]).compareTo(data[j+1])>0)
105	      {
106	       hold= data[j+1];
107	       data[j+1]=data[j];
108	       data[j]=hold;
109	      }       
110	   }
111     } 
112	 return true;	  	
113  }
114
115
116 
117}