java 如何使用该元素的字段值在 ArrayList 中查找元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25676911/
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-11-02 08:26:31  来源:igfitidea点击:

How to find an element in an ArrayList by using a field value of that element?

javaobjectarraylist

提问by Francis

I am writing a program in Java which accepts user-inputted String in one class.

我正在用 Java 编写一个程序,它在一个类中接受用户输入的字符串。

On a separate class, I have an array-list of class type 'Item' which contains elements of type String (itemName), int, and double. I was wondering if there was a way to either convert the user-inputted String to an object of type 'Item' (I've heard it's difficult), or if there was a way to access the individual String element itemName of the array-list to compare it to the user-inputted String.

在一个单独的类中,我有一个类类型“Item”的数组列表,其中包含 String (itemName)、int 和 double 类型的元素。我想知道是否有办法将用户输入的 String 转换为“Item”类型的对象(我听说这很难),或者是否有办法访问数组的单个 String 元素 itemName-列表以将其与用户输入的字符串进行比较。

Item.java

项目.java

public class Item {
    private String name;
    private int monetaryValue;
    private double weight;

    // Getters and Setters
    // ...

    // Other methods
    // ...
}

回答by Stephan

I would not use Reflection here: it's using a bazooka for killing a mosquito. I'd rather use plain Java.

我不会在这里使用反射:它使用火箭筒杀死蚊子。我宁愿使用普通的Java。

Check this example below:

检查下面的这个例子:

List<Item> myList = new ArrayList<Item>();
String userInputValue;

// * Add some items to myList
// ...

// * Get user input value
// ...

// * Access the array list
int len=myList.size();
for(int i=0; i<len; i++) {
    if (myList.get(i).getItemName().equals(userInputValue)) {
        // Do something ...
    }
}

回答by Wai Ho Leung

To create an Itemfrom user input, you can do:

要从Item用户输入创建一个,您可以执行以下操作:

String input1;
String input2;
String input3;

// Assign user input to input1, input2, input3

String itemName = input1;
int data2 = Integer.parseInt(input2);
double data3 = Double.parseDouble(input3);

Item myItem = new Item(itemName, data2, data3);

To access elements from array list, you can do:

要访问数组列表中的元素,您可以执行以下操作:

List<Item> items;
String input;

// Populate items

// Assignment user input to "input" variable.

for (Item item : items) {
    if (item.getItemName().equals(input)) {
        // Do something...
    }
}

回答by Dici

You can of course build Itemobjects from user input if you define an input format like [name:string] [i:int] [d:double](example : john 5 3.4). You then just have to split this String and use Integer.parseInt and Double.parseDouble to parse the two last arguments.

Item如果您定义输入格式[name:string] [i:int] [d:double](例如:),您当然可以从用户输入构建对象john 5 3.4。然后你只需要拆分这个字符串并使用 Integer.parseInt 和 Double.parseDouble 来解析最后两个参数。