public class ContactList {
private ContactNode head;
private ContactNode last;
public ContactNode current;
public ContactList value;
public ContactList() {}
public void addNode(ContactNode input) {
if (this.head == null) {
this.head = input;
this.last = input;
} else last.setNext(input);
input.setPrev(last);
this.last = input;
}
public void traverse() {
System.out.println();
current = this.head;
while (current != null) {
System.out.print(current.getName() + " ");
System.out.println("");
current = current.getNext();
}
System.out.println();
}
public void insertNewFirstNode(String value) {
ContactNode newNode = new ContactNode(value);
head = newNode;
if (last == null) {
last = head;
}
}
public void sort() {
ContactList sorted = new ContactList();
current = head;
while (current != null) {
int index = 0;
if ((current.getName() != null)) {
index = this.current.getName().compareTo(current.getName());
if (index == 1) {
sorted.insertNewFirstNode(current.getName());
}
current = current.getNext();
} else if ((current != null)) {
System.out.print(sorted + "\n");
}
}
} // end contactList
主要方法:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class ContactMain {
public static void main(String[] args) {
try {
FileReader filepath = new FileReader("data1.txt");
Scanner k = new Scanner(filepath);
ContactList myList = new ContactList();
while (k.hasNextLine()) {
String i = k.nextLine();
myList.addNode(new ContactNode(i));
}
myList.traverse();
myList.sort();
myList.traverse();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. ");
}
}
}
节点类:
public class ContactNode {
private String name;
public int index;
private ContactNode prev;
public ContactNode next;
ContactNode(String a) {
name = a;
index = 0;
next = null;
prev = null;
}
public ContactNode getNext() {
return next;
}
public ContactNode getPrev() {
return prev;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
public void setNext(ContactNode newnext) {
next = newnext;
}
public void setPrev(ContactNode newprevious) {
prev = newprevious;
}
public void setName(String a) {
name = a;
}
public void setIndex(int b) {
index = b;
}
}
我正在制作一个有趣的程序,它从文本文件中读取联系信息并将它们放入链接列表中。我想创建一个sort()
方法来按字母顺序对每个节点或名称进行排序。我做了大量的研究,而且我的方法只打印代码:ContactList@282c0dbe
,与我的文本文件一样多行。
答案 0 :(得分:0)
You need custom Comparator
for sorting,要精确打印List
,您需要在toString()
课程中实施ContactList
答案 1 :(得分:0)
什么是ContactList@282c0dbe
?
最后是符号和哈希码的类名,对象的哈希码.Java中的所有类都直接或间接地从Object类继承。 Object类有一些基本方法,如clone(),toString(),equals(),..等。对象中的默认toString()
方法打印“class name @ hash code”.
什么是解决方案?
您需要覆盖toString
类中的ContactList
方法,因为它将以您可以理解的可读格式为您提供有关对象的明确信息。
覆盖toString
:
帮助程序员记录和调试Java程序
由于 toString 是在 java.lang.Object 中定义的,并且没有提供有价值的信息,所以它是 为子类重写它的好习惯。
@override
public String toString(){
// I assume name is the only field in class test
return name + " " + index;
}
对于排序,您应该实现Comparator接口,因为您的对象没有natural ordering。更好的意义是,如果要定义外部可控排序行为,则可以覆盖默认排序行为