家伙! 我正在为大学做一个课程,我被困在某事上。我有一个类的层次结构和一个ArrayList,其中存储了来自这些类的对象。我的代码打印出对象'存储在ArrayList中的详细信息,但我必须根据字符串字段将它们打印出来,我不知道该怎么做。我需要根据LibraryItem类中的title字段打印细节,并指定我需要使用Java类库。我查看了一些内容,根据我所看到的情况,我猜测我需要使用Comparable,但我不知道它是如何工作的...... 以下是代码的一部分:
public class LibraryItem {
private String title;
private String itemCode;
private int timesBorrowed;
...
public void printDetails()
{
System.out.println("\nTitle: " + title);
System.out.println("Item code: " + itemCode);
System.out.println("Cost: " + cost);
System.out.println("Times borrowed: " + timesBorrowed);
System.out.println("On loan: " + onLoan);
}
}
...
public abstract class AudioVisual extends LibraryItem{
private int playingTime;
public AudioVisual()
{
super();
playingTime = 80;
}
public void printDetails()
{
super.printDetails();
System.out.println("Playing time: " + playingTime);
}
...
public class CD extends AudioVisual{
private String artist;
private int noOfTracks;
public CD()
{
super();
artist = "The Animals";
noOfTracks = 9;
}
public void printDetails()
{
super.printDetails();
System.out.println("Artist: " + artist);
System.out.println("Number of tracks: " + noOfTracks);
}
...
public class DVD extends AudioVisual{
private String director;
public DVD()
{
director = "Director1";
}
public void printDetails()
{
super.printDetails();
System.out.println("Director: " + director);
}
...
public class Library
{
private ArrayList<LibraryItem> itemList;
public Library()
{
itemList = new ArrayList<LibraryItem>();
}
public void printAllDetails()
{
for (LibraryItem item: itemList)
{
item.printDetails();
}
}
同样在ArrayList中添加CD和DVD对象。提前谢谢!
答案 0 :(得分:2)
Collections.sort上有一个需要Comparator的超载,你可以使用它,
Collection.sort(items, new Comparator<LibraryItem>{
@Override
public int compare(LibraryItem a, LibraryItem b) {
return a.title.compareTo(b.title);
}
}
如果您使用的是Java 8,那么使用lambdas的版本就会更简洁。
Collections.sort(items,(item1,item2) -> item1.title.compareTo(item2.title));
答案 1 :(得分:1)
您可以通过两种方式实现:
无论您选择哪种方式,您的实施都会像:
public int compare(LibraryItem item1, LibraryItem item2) {//if you are implementing Comparator
return item1.getTitle().compareTo(item2.getTitle());//if you want to sort item by title
}
然后在打印列表之前,您可以将它们排序为:
Collections.sort(itemList, <comparator object>);//if using comparator or you could omit passing comparator object.
//iterate and print items
答案 2 :(得分:0)
Streams方式(原始集合未触及)
itemList.stream()
.sorted(Comparator.comparing(LibraryItem::getTitle))
.forEachOrdered(LibraryItem::printDetails);
收集品排序(即有副作用)
Collections.sort(itemList, Comparator.comparing(LibraryItem::getTitle));
for (LibraryItem item : itemList) {
item.printDetails();
}
答案 3 :(得分:-1)
employees.stream()收集(Collectors.summingInt(员工::的getSalary)));
这里的员工表示清单。你可以用group by或类似的东西替换summingInt,Employee是类名,getSalary是你需要排序的属性。
进一步参考,您可以浏览
http://download.java.net/lambda/b88/docs/api/java/util/stream/Collectors.html