I a method that takes a list of numbers (e.g. ArrayList) and converts it into a sorted set (e.g. TreeSet) and returns it. I wrote code, but I'm having some problems.
public TreeSet getSort (ArrayList list){
TreeSet set =new TreeSet(list);
return set;
My problem is in main:
ArrayList List = new ArrayList();
List.add(5);
List.add(55);
List.add(88);
List.add(555);
List.add(154);
System.out.println("the TreeSet of ArrayList is : " + getSort(List));
You need to have the class instance to call the getSort() method or make the getSort() to static
Do like
System.out.println("the TreeSet of ArrayList is : "+ new classname().getSort(List));
or make the method static
public static TreeSet getSort (ArrayList list){
TreeSet set =new TreeSet(list);
return set;
}
You're probably getting an error because getSort() isn't static, so it can't be called from main(). Beyond this, you shouldn't use raw types, parametrize your lists and sets:
ArrayList<Integer> list = ...
TreeSet<Integer> set = ...
You should be getting warnings about this.
In fact, I would make this method totally generic:
public static <V extends Comparable<V>> TreeSet<V> getSort(List<V> list) {
return new TreeSet<>(list);
}
Lastly, remember to follow naming conventions: local variable names should start with a lowercase letter (i.e. list and not List).
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