Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converts ArrayList into a sorted set (TreeSet) and returns it

Tags:

java

arraylist

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));
like image 828
Good tree Avatar asked Jan 22 '26 02:01

Good tree


2 Answers

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;
         }
like image 155
Nambi Avatar answered Jan 24 '26 15:01

Nambi


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).

like image 33
arshajii Avatar answered Jan 24 '26 15:01

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!