我正在尝试使用 Java 中的 ArrayList 按名称、颜色和重量对 Fruit 类的特征进行排序。在创建 Fruit 类的实例之前,名称、颜色和重量都从用户以字符串形式在一行中读入。然后我需要将 Fruit 对象添加到 ArrayList,并按照我之前提到的顺序对它们进行排序。换句话说,首先按名称按字母顺序排列,然后按颜色排列,最后按重量排列。
我不完全确定如何从 ArrayList 类中实现 sort() 方法。你对我有什么建议吗?或者也许有任何教程可以建议我在哪里可以提高我对 sort() 和 ArrayLists 的理解?
代码如下。
谢谢!
import java.util.*;
/**creates instances of the Fruits class, and stores the
* resulting objects in an array which can be ordered
* firsting alphebetically by name, then by colour, and
* finally, in ascending order by weight
**/
public class Driver
{
public static void main(String[]args)
{
Scanner s = new Scanner(System.in);
int input = 0;
ArrayList fruitInfo = new ArrayList();
do
{
System.out.println("Enter option: (1) add fruit (2) quit:");
input = s.nextInt();
s.nextLine();
switch(input)
{
case 1:{
System.out.println("Enter name, colour and mass in kg separated by a `enter code here`space");
String in = s.nextLine();
String[] temp = in.split(" ");
//create a new instance of the fruit class and add it to the `enter code here`<ArrayList> {@link ArrayList}, fruitInfo
fruitInfo.add(new Fruit(temp[0], temp[1], temp[2]));
break;
}
case 2:{
break;
}
default: System.out.println("Input incorrect. Try again.");
}
}
while(input!=2);
}
}
/* Class Fruits
* a class modelled on the characteristics of fruit
* each fruit has a name, colour and mass, which are
* stored as <Strings>
**/
public class Fruit
{
private String name;
private String col;
private String kg;
/* Constructor
* constructs an instance of the Fruit class
* using user defined characteristics
**/
public Fruit(String name, String colour, String mass)
{
this.name=name;
col=colour;
mass=kg;
}
}