I created my own MyArrayList but it can not be sorted. A normal Arraylist can be sorted by Collections.sort but mine can not. Could some one tell me where is wrong?
import java.util.*;
public class TestMyArrayList
{
public static void main(String[] args){
String[] subjects = {"EIE320", "EIE558", "EIE375", "EIE424"};
Integer[] marks = {90,85,70,80};
MyArrayList<String> sList = new MyArrayList<String>(subjects);
Collections.sort(sList);
sList.print();
MyArrayList<Integer> mList = new MyArrayList<Integer>(marks);
Collections.sort(mList);
mList.print();
}
}
public class MyArrayList<E> extends ArrayList<E>
implements List<E>
{
private List<E> data;
public MyArrayList()
{
}
public MyArrayList(E[] inputdata){
super();
data = new ArrayList<E>();
for(E e:inputdata){
data.add(e);
}
}
public void print(){
for(Iterator iter = data.iterator();iter.hasNext();){
System.out.print(iter.next() + " ");
}
System.out.println(" ");
}
}
The constructor of MyArrayList is wrong. Since you are extending ArrayList, you shouldn't create another ArrayList instance in the MyArrayList constructor. Just add the elements to this ArrayList.
When you call Collections.sort() on your MyArrayList instance, it doesn't sort the data member List.
public MyArrayList(E[] inputdata){
super();
for(E e:inputdata){
super.add(e);
}
}
Your data member is not needed. You would only need such a member if you use composition instead of inheritance, in which case your class wouldn't extend ArrayList.
You should also modify your print method :
public void print(){
for(Iterator iter = iterator();iter.hasNext();){
System.out.print(iter.next() + " ");
System.out.println(" ");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With