Java 从 ArrayList 方法类型返回 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22469208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:55:34  来源:igfitidea点击:

Return ArrayList from ArrayList method type

javamethodsarraylistreturn

提问by user3066571

I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.

我正在制作一个使用 ArrayList 作为卡片组的小卡片组程序。对我设置的限制之一是我“处理”卡片的方法必须是 Arraylist 类型。我遇到的问题是我不知道如何只从 ArrayList 返回一个特定的索引值。见下文。

public ArrayList deal(int n, boolean up){
    Card card0 = new Card();
    boolean cardFace = card0.state(up);
    return al.get(0);  //<-- This doesn't work, Netbeans says that it is a string type
                            //not an ArrayList type.  The only thing it will actually
                            //allow me to return is:
    return.al;  // But this doesn't work, I don't need to return the whole list,
                // just the first element, but Netbeans calls that a String type, not
                // ArrayList

So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.

那么我怎样才能返回 List 的第一项并且仍然是正确的类型呢?其余的代码无关紧要,只是 Method 类型和 return 语句。

EDIT: As requested

编辑:根据要求

package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
    ArrayList<String> al = new ArrayList<>();
    public void shuffle(){
        Collections.shuffle(al);
    }
    public String displayDeck(){
        String returnDeck = "";
        for(int i = 0; i < al.size(); i++){
            String printDeck = al.get(i);
            returnDeck += printDeck;
        }
        return returnDeck;
    }
    public ArrayList deal(int n, boolean up){
        Card card0 = new Card();
        boolean cardFace = card0.state(up);
        return al.get(0);
    }
    public void populate(){
        al.add(0, "Ace of Spades");
        al.add(1, "Two of Spades");
        al.add(2, "Three of Spades");
        //yadaa yadaa

采纳答案by Juned Ahsan

If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:

如果您无法更改签名并且必须返回一个数组列表,那么您可以创建一个只有一个元素的数组列表并返回它。像这样的东西:

ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;

Does not look great to me :-(

对我来说看起来不太好:-(

回答by Jason C

In your specific case, alis an ArrayList<String>. That means al.get(...)returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayListand add your single string to it and return that.

在您的特定情况下,al是一个ArrayList<String>. 这意味着al.get(...)返回一个String. 但是,您的方法被声明为返回一个ArrayList,而不是一个String。您要么需要将方法返回类型更改为String,要么需要构造一个新的ArrayList并将您的单个字符串添加到其中并返回该字符串。

Your declared return type needs to match the object you are returning. So for example:

您声明的返回类型需要与您要返回的对象相匹配。例如:

 ArrayList<String> al = ...;

 String getSingleItem (int index) {
     return al.get(index);
 }

 ArrayList<String> getSingleItemAsArrayList (int index) {
     ArrayList<String> single = new ArrayList<String>();
     single.add(al.get(index));
     return single;
 }

 ArrayList<String> getItems () {
     return al;
 }

By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.

顺便说一句,通常最好将类型参数指定为ArrayList,例如ArrayList<Whatever>,因为这可以为您节省大量围绕/未检查转换的转换,并且将为您提供编译时类型的检查。

回答by mreiss

Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.

是否有理由必须返回 ArrayList?从本质上讲,您正在尝试创建一个方法,该方法接受一副牌,选择一张牌,然后返回一副牌。您可以尝试使用上面提到的 subList 方法。您可以创建一个仅包含您想要的卡片的新 ArrayList,但这不是很有效。或者,如果您的目标是实际返回整个牌组,但正确的卡片在顶部(也就是在 ArrayList 的第一个位置),那么网上有很多关于重新排列 ArrayList 中的值的信息。

EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.

编辑:根据您的完整代码,目标似乎是将第一张卡正面朝上。你应该这样做(不会为你做作业!)然后返回该方法接收的 ArrayList。IRL,想象给某人一副牌,他们将第一张牌正面朝上翻转,然后将牌组还给你。

回答by SAI KUMAR REDDY NOSSAM

//ADDING AND deleting employees //Displaying employee list

//添加和删除员工 //显示员工列表

public class EployeeDB { static ArrayList e = new ArrayList<>();

公共类 EployeeDB { 静态 ArrayList e = 新 ArrayList<>();

public static boolean addEmployee(Employee e1) {

    e.add(e1);
    System.out.println("Employee added");
    return true;

}

public static boolean deleteEmployee(int ecode) {
    int temp = 0;
    for (int i = 0; i < e.size(); i++) {

        if (e.get(i).getID() == ecode) {
            temp = temp + 1;
            e.remove(i);
            break;
        }
    }
    if (temp == 1)
        System.out.println("Emp deleted");
    else
        System.out.println("Deletion unsuccessful, check ecode again");
    return true;

}

public static String showPaySlip(int ecode) {
    double salary = 0;
    int temp = 0;
    for (int i = 0; i < e.size(); i++) {
        if (e.get(i).getID() == ecode) {
            temp = temp + 1;
            salary = e.get(i).getSalary();
            break;
        }
    }
    if (temp == 1)
        return "Salary is" + salary;
    else
        return "No employye found with the specified ecode";

}

public static ArrayList<Employee> listAll() {

    return e;

}

public static void main(String[] args) {
    Employee e1 = new Employee();
    e1.setID(20);
    e1.setName("sai");
    e1.setSalary(150.00);
    addEmployee(e1);
    Employee e2 = new Employee();
    e2.setID(30);
    e2.setName("kumar");
    e2.setSalary(1500.00);
    addEmployee(e2);
    deleteEmployee(30);
    System.out.println(showPaySlip(30));

    for (int i = 0; i < e.size(); i++)
        System.out.println(
                listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());

}

}

}