Question: 1)Sort an array list of strings by increasing length. In java code Heres what i have so far but I can't figure out the compare

1)Sort an array list of strings by increasing length. In java code

Heres what i have so far but I can't figure out the compare method

import java.util.*;

public class Sort implements Comparator

{

public int compare(Arraylist a, ArrayList b)

{

if(a.length() < b.length())

{

return -1;

}

else

if(a.length() == b.length())

{

return 0;

}

else

{

return 2;

}

}

public static void main(String [] args)

{

System.out.println("ArrayList1 before sort: ");

ArrayList a = new ArrayList<>();

a.add("kind");

a.add("lift");

a.add("gym");

a.add("on");

//Print arraylist before sort

System.out.print(a);

System.out.println(" ");

//Print arraylist after sort

System.out.println("ArrayList1 after sort:");

Collections.sort(a);

System.out.println(a.toString());

System.out.println("Arraylist 2 before sort: ");

ArrayList b = new ArrayList<>();

b.add("bat");

b.add("page");

b.add("car");

b.add("new");

//Print arraylist2 before sort

System.out.print(b);

System.out.print(" ");

//Print arraylist2 after sort

System.out.println(" ");

System.out.println("Arraylist2 after sort: ");

Collections.sort(b);

System.out.println(b.toString());

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!