你好,我有一个关于使用类型实现的类的问题。 我在下面有类代码和Main。我正在尝试读取文本文件,该文件包含Main中的状态行,例如“ Alaska,Ak,10”。然后将对象加载到数组中并使用sort。我想通过输出数组列表中的所有实例对象来检查的正确实现。我无法理解如何通过输出实例对象来检查实现是否正确。
package com.company;
public class State implements Comparable<State> {
public String name;
public String code;
public int region;
public State(String name, String code, int region) {
this.name = name;
this.code = code;
this.region = region;
}
@Override
public String toString() {
return "State{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
", region=" + region +
'}';
}
@Override
public int compareTo(State o) {
while (this.region != o.region) {
if (this.region < o.region)
return o.region;
else
return this.region;}
if(this.code.compareTo(o.code)< 0 )
return -1;
else if(this.code.compareTo(o.code) > 0)
return 1;
else return 0;}}
在主屏幕中:
public static void main(String[] args) {
File myStates = new File("states.txt");
ArrayList<State> stateList = new ArrayList<>();
try { Scanner input = new Scanner(myStates);
while (input.hasNextLine()) {
String line = input.nextLine();
String[] array = line.split(",");
int x = Integer.parseInt(array[2]);
stateList.add(new State(array[0], array[1],x));
java.util.Collections.sort(stateList);
for(State s : stateList)
System.out.println(s);