简体   繁体   English

如何在单独的行上返回 ArrayList 的对象

[英]How to return the Objects of an ArrayList on separate lines

I have created a program that sorts trading cards and places them in a collection that is then compared to other collections to look for duplicates.我创建了一个程序,对交易卡进行分类并将它们放在一个集合中,然后将其与其他 collections 进行比较以查找重复项。 I have had no problems up until my final toString method.在我最后的 toString 方法之前,我没有遇到任何问题。 My issue is that I cannot seem to get the return statement to separate the various cards onto their own separate lines.我的问题是,我似乎无法获得将各种卡片分开到各自单独行的返回声明。 instead of Alan Turing, Grace Hopper, Ada Lovelace, I need:而不是 Alan Turing、Grace Hopper、Ada Lovelace,我需要:

Alan Turing艾伦·图灵

Grace Hopper格蕾丝·霍珀

Ada Lovelace艾达洛夫莱斯

Below is a copy of my code.下面是我的代码的副本。 I am fairly new to java so I apologize for any lack of knowledge pertaining to methods specific to this, but I have only found ones using System.out.println, and not mentioning return in any way.我对 java 相当陌生,所以对于缺乏与此特定方法相关的知识,我深表歉意,但我只找到了使用 System.out.println 的方法,并没有以任何方式提及返回。 My problem lies in the method defined by **.我的问题在于**定义的方法。 I appreciate any and all help and am sorry if this question is not 100% clear.我感谢任何和所有的帮助,如果这个问题不是 100% 清楚,我很抱歉。 (I have tried my own research to no avail!) (我已经尝试过自己的研究无济于事!)

// First Class
public class Card implements Comparable<Card> {
    private String name;
    private String nationality;
    private int yearBorn;
    private int yearDied;

    public Card(String name, String nationality, int yearBorn, int yearDied) {
        this.name=name;
        this.nationality=nationality;
        this.yearBorn=yearBorn;
        this.yearDied=yearDied;
    }
    public int compareTo(Card c) {
        if (this.name.equals(c.name)) return 0;
        else if (this.name.compareTo(c.name)>0) return 1;
        else return -1;
    }

    public String toString() {
        return String.format("%s (%d - %d) - %s", name, yearBorn, yearDied, nationality);
    }

}
// Second Class

import java.util.ArrayList;
import java.util.List;

public class CardCollection {
    private String owner;
    private List<Card> myCollection;

    public CardCollection(String owner) {
        this.owner = owner;
        this.myCollection = new ArrayList<>();

    }

    public boolean addCard(Card c) {
        int p = 0;
        while (p < myCollection.size()) {
            int q = myCollection.get(p).compareTo(c);
            if (q == 0) {
                return false;
            } else if (q > 0) {
                myCollection.add(p, c);
                return true;
            }
            p++;
        }
        myCollection.add(c);
        return true;
    }

    public void removeCard(int r) {
        myCollection.remove(r);
    }

    public int getSize() {
        return myCollection.size();
    }

    public ArrayList<Card> mergeCollections(CardCollection cc) {
        ArrayList<Card> dupes = new ArrayList<>();
        while (cc.getSize() > 0) {
            Card c = cc.myCollection.remove(0);
            if (myCollection.contains(c)) {
                dupes.add(c);
            }
            else myCollection.add(c);
        }
        return dupes;
    }
    **public String toString() {
            String s = "";
            for (int i = 0; i < owner.length(); i++) {
                s += "-";
            }
            return String.format("%s\n%s\n%s\n", owner, s, myCollection);**
    }
}
// Runner Class
import java.util.ArrayList;
public class CCRunner {
    public static void main(String[] args) {
        CardCollection c1 = new CardCollection("Alan");
        CardCollection c2 = new CardCollection("Grace");
        Card turing = new Card("Alan Turing","British",1912,1954);
        Card hopper = new Card("Grace Hopper","American",1906,1992);
        Card vonneumann = new Card("John Von Neumann","Hungarian",1903,1957);
        Card shannon = new Card("Claude Shannon","American",1916,2001);
        Card johnson = new Card("Katherine Johnson","American",1918,-1);
        Card lovelace = new Card("Ada Lovelace","British",1815,1852);
        Card cerf = new Card("Vint Cerf","American",1943,-1);
        Card brin = new Card("Sergey Brin","Russian",1973,-1);
        c1.addCard(turing);
        c1.addCard(vonneumann);
        c1.addCard(shannon);
        c1.addCard(johnson);
        c1.addCard(cerf);
        c1.addCard(brin);
        c2.addCard(cerf);
        c2.addCard(lovelace);
        c2.addCard(johnson);
        c2.addCard(vonneumann);
        c2.addCard(hopper);
        System.out.println(c1);
        System.out.println(c2);
        ArrayList<Card> dupes = c1.mergeCollections(c2);
        System.out.println(c1);
        System.out.println(c2);
        System.out.println("Duplicates:\n-----------");
        for (Card c : dupes) {
            System.out.println(c);
        }
    }
}

This is run in a separate class, but I don't think it will elucidate my problem to include it.这是在单独的 class 中运行的,但我认为包含它并不能说明我的问题。 Let me know if I am wrong.让我知道我是否错了。

You can either change your implementation of toString() of your CardCollection class.您可以更改CardCollection class 的toString()的实现。 Examples:例子:

Loop again, this time over the List :再次循环,这次是在List上:

public final String toString() {
  String s = "";
  for (int i = 0; i < owner.length(); i++) {
    s += "-";
  }
  for (int i = 0; i < myCollection.size(); i++) {
    s += "\n" + myCollection.get(i);
  }
  return String.format("%s\n%s\n", owner, s);
}

Using a stream (requires an additional import java.util.stream.Collectors; ):使用 stream(需要额外import java.util.stream.Collectors; ):

public final String toString() {
  String s = "";
  for (int i = 0; i < owner.length(); i++) {
    s += "-";
  }
  return String.format("%s\n%s\n%s\n",
                       owner,
                       s,
                       myCollection.stream()
                                   .map(Card::toString)
                                   .collect(Collectors.joining("\n")));
}

Or you can @Override the toString() method of the ArrayList , also in your CardCollection class.或者您也可以在您的CardCollection ArrayList中 @Override @OverridetoString()方法。 Example:例子:

this.myCollection = new ArrayList<>(){
                      @Override
                      public String toString(){
                        String s = "";
                        if (size() > 0) s = get(0).toString();
                        for (int i = 1; i < size(); i++) {
                          s += "\n" + get(i).toString(); 
                        }
                        return s;
                      }
                    };

All examples will result in this for Alan (before the merge):所有示例都将导致 Alan(在合并之前):

Alan
----
Alan Turing (1912 - 1954) - British
Claude Shannon (1916 - 2001) - American
John Von Neumann (1903 - 1957) - Hungarian
Katherine Johnson (1918 - -1) - American
Sergey Brin (1973 - -1) - Russian
Vint Cerf (1943 - -1) - American

Note: I'd personally go with changing the implementation of toString() of the CardCollection class.注意:我个人 go 会更改CardCollection class 的toString()的实现。 I would also perfer the way tquadrat did it in their answer .我也更喜欢tquadrat在他们的回答中这样做的方式。 The overriding of ArrayList looks to messy in my opinion, and keeping the stringrepresentation in the toString() method makes more sense to me.在我看来,覆盖ArrayList看起来很混乱,在toString()方法中保留字符串表示对我来说更有意义。

Try this as a replacement to the marked toString() implementation:试试这个作为标记toString()实现的替代:

…
public final String toString() 
{
    var s = "-".repeat( owner.length() );
    var joiner = new StringJoiner( "\n", String.format( "%s%n%s%n", owner, s ), "" );
    for( var c : myCollection ) joiner.add( c.toString() );
    var retValue = joiner.toString();

    return retValue;
}

Basically, the output would look like this:基本上,output 看起来像这样:

<owner>
------- 
<collectible1> 
<collectible2> 
<…>

If you are using a Java version before Java 11, you may need to replace var with the respective types.如果您使用的是 Java 11 之前的 Java 版本,则可能需要将var替换为相应的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM