Francis
Francis

Reputation: 83

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

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

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.java

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

    // Getters and Setters
    // ...

    // Other methods
    // ...
}

Upvotes: 3

Views: 26422

Answers (3)

Wai Ho Leung
Wai Ho Leung

Reputation: 46

To create an Item from user input, you can do:

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...
    }
}

Upvotes: 2

Stephan
Stephan

Reputation: 43023

I would not use Reflection here: it's using a bazooka for killing a mosquito. I'd rather use plain 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 ...
    }
}

Upvotes: 5

Dici
Dici

Reputation: 25950

You can of course build Item objects 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.

Upvotes: 0

Related Questions