i have an arraylist, that stores objects from a class called prematricula and every object stored has name and province how i can do to pass the name of the province and the method return the names of the students sorted alfabethically...
please if someone can help me....

Recommended Answers

All 9 Replies

Create method that will take an ArrayList as an agrument and will have ArrayList as return value. Something along the line of this method showed by masijade in this thread

Use java.lang.Comparable interface and java.util.Arrays class.

Here is sample code:

Emp.java

public class Emp implements Comparable
{
  private String name;
  private String city;

  public Emp(){}
  public Emp(String name,String city) { 
        this.city=city; this.name=name;}
  public int compareTo(Object p)
  {
     Emp a=(Emp)p;
     return name.compareTo(a.name);
  }
  public String getName() { return name;}
  public String getCity() { return city;}
}

and
Sort2.java

import java.util.*;

public class Sort2
{
  public static void main(String []args)  
  {
     ArrayList<Emp> a=new ArrayList<Emp>();
     a.add(new Emp("Amar","Zar"));
     a.add(new Emp("Zalar","Ara"));
     a.add(new Emp("Bab","Ac"));
     a.add(new Emp("Japp","rc"));

     Object []arr=a.toArray();
     Arrays.sort(arr);
     List b=Arrays.asList(arr);
    // Print elements
     for(int i=0;i<b.size();i++)
      {
         Emp k=(Emp)b.get(i);
         System.out.println(k.getName() + " " + k.getCity());
      }
     // Another way to print elements
      for(Iterator e=b.iterator();e.hasNext();)
      {
        Emp k=(Emp)e.next();
        System.out.println(k.getName() + " " + k.getCity());
      }
  }
}

Yes, as long as it's not JME implementing Comparable or creating a Comparator is the way to go, but there is no reason to use Arrays. Collections also has sort methods. No reason to convert to an array and back to a list, leave it as a list.

I am sorry. Which collection class has sort method?

I am sorry. Which collection class has sort method?

Collections

That is a Class in and of itself, much like Arrays.

commented: Great eyes! +3

Thanks masijade.

I appreciate your help.

Thanks again.

If I was on chapter 7 of SCJP study guide I would have answered correctly ;) , but I'm only chapter 3 :$

If I was on chapter 7 of SCJP study guide I would have answered correctly ;) , but I'm only chapter 3 :$

Technically, you were correct, and, in fact, that way may even be quicker than using the Collections manner, it's just longer to write, and not quite as "code reusable". ;)

thanks to everybody

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.