使用 ArrayList 存储变量 [英] Using ArrayList to store variables

查看:29
本文介绍了使用 ArrayList 存储变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个项目来存储对象数组,可能在一个数组列表中.

I'm coding a project to store an array of objects, probably in an arraylist.

因此,我的对象具有数据元素、getter 和 setter.我不知道如何访问对象的元素.

So, my object has data elements, getters and setters. I do not have an idea how to access the elements of the object.

例如,我的对象是一本书,它具有以下数据元素.

For example my object is a book which has the following data elements.

Book
->Author
->Price
->Date

如果某本书的价格发生变化,如何更新arrayList?我需要一个二维 arrayList 吗?我认为 indexOf 不起作用,因为它是一个对象?不太确定.

If the price of a certain book changes, how do I update the arrayList? Do I need a 2d arrayList? I think indexOf would not work because it is an object? Not really sure.

我只是一个编程新手,所以我不确定 arrayList 是否是正确的数据结构.非常感谢您阅读本文,您的帮助将不胜感激.

I'm just a newbie in programming, so I'm not sure if arrayList is the right data structure to use. Thank you very much for reading this, your help will be appreciated.

推荐答案

您可以通过索引访问 ArrayList 中的对象.假设您想要第三本书:

You can access an object in an ArrayList by it's index. Say you want the third book:

List<Book> lisOfBooks = someFunctionWhichGetsListOfBooks();

Book book = listOfBooks.get(2);

(记住java中索引从0开始)然后你可以这样做:

(Remember indexes start at 0 in java) Then you can do:

String Author = book.getAuthor();

或设置价格:

book.setPrice(newPrice);

如果您不知道特定书籍在列表中的哪个位置,您有 2 个选择:1) 遍历列表直到找到您想要的书籍或 2) 您可以使用 HashMap.但是你需要决定这本书的重点(是什么让每本书独一无二?).假设您将按 id 查找书籍.然后你可以把你所有的书放在一个以整数 id 为键的 HashMap 中:

If you do not know where in the list the particular book is you have 2 choices: 1) iterate through the list until you find the book you want or 2) you can use a HashMap. But you need to decide what to key the book on (what makes each book unique?). Let's say you'll be looking up books by id. Then you can put all your books in a HashMap keyed by an Integer id:

HashMap<Integer, Book> bookHash = new HashMap<Integer, Book>();

for (Book book : listOfBooks) {
    bookHash.put(book.getId(), book);
}

然后检索您可以执行的任何书籍:

Then to retrieve any book you can do:

Book book = bookHash.get(bookId);

显然,这假设您的 Book 类具有适当的 getter 和 setter 方法.例如:

Obviously this assumes your Book class has appropriate getter and setter methods. E.g:

public class Book {

   private int id;
   private String author;
   ...

   public String getAuthor() {
      return author;
   }

   public void setPrice(price) {
     this.price = price;
   }

   ...

} 

这篇关于使用 ArrayList 存储变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆