我正在编写一个程序来为我设置一个实验,我想按字母顺序输入我输入的主题(或人物)。我有一个主题类型的数组列表,我想用它们的名字按字母顺序排列。

import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Experiment
{
public Random number;
public ArrayList<String> allSubject;
public ArrayList<Subject> allSubjects,alphaSubjects;
public ArrayList<Group> experiment;
public Integer value;
public HashMap<Integer,Subject> matched;
private ArrayList<Integer> numbers;
/**
 * Make a new Experiment.  Then use method addSubject to add
 * Subjects to your experiment.  Then call the assignGroups
 * method to assign Subjects to each group.
 */
public Experiment()
{
    number = new Random();
    numbers = new ArrayList<Integer>();
    experiment = new ArrayList<Group>();
    matched = new HashMap<Integer,Subject>();
    allSubjects = new ArrayList<Subject>();
    allSubject = new ArrayList<String>();
    alphaSubjects = new ArrayList<Subject>();
}

/**
 * Alphabetizes the list of Subjects based on their
 * name input by the user.  As of right now, this method
 * is case sensitive meaning Strings starting with
 * capitals will be listed before those without capitals.
 */
private void alphabetize()
{

           Collections.sort(allSubject);

        //compare the String arraylist to the subject arraylist to reset the subject arraylist indeces in alphabetical order.

       for(int i =0;i<allSubject.size();i++)
       {
        String theName = allSubject.get(i);
         for(Subject subject:allSubjects)
        {
          if(subject.getName().toLowerCase().contains(theName))
         {
            alphaSubjects.add(new Subject(subject.getName(),subject.getDescription()));
         }
        }

     }
}
/**
 * Adds a new Subject to the experiment.
 */
public void addSubject(String name, String description)
{
    allSubjects.add(new Subject(name,description));
    allSubject.add((name.toLowerCase()));
}


因此,不必将主题添加到数组列表中,而不必从该主题中删除名称并将其添加到完全不同的数组列表中,而是可以通过主题名称按字母顺序排序。

哦,这是课程:主题。

public class Subject
{
public final String name;
public final String description;
public Subject(String name, String description)
{
    this.name = name;
    this.description = description;
}
public Subject(int aNumber)
{
    name = "Subject" + aNumber;
    aNumber++;
    description = "default";
}
public String getName()
{
    return name;
}
public String getDescription()
{
    return description;
}


}

最佳答案

您可以使用自己的比较器将主题ArrayList与SortedList(http://www.glazedlists.com/documentation/tutorial-100#TOC-Sorting-Tables-Sorting-Tables)包装在一起。

SortedList sortedSubjects = new SortedList<Subject>(allSubjects,new Comparator<Subject>() {
        @Override
        public int compare(Subject left, Subject right) {
            return left.getName().compareTo(right.getName);
        }
    });

09-25 21:23