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

查看:60
本文介绍了使用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);

如果您不知道特定书在列表中的何处,则有两种选择:1)遍历列表直到找到所需的书,或者2)您可以使用HashMap.但是,您需要决定在哪本书上键入密码(是什么使每本书都独一无二?).假设您要按ID查找图书.然后,您可以将所有书籍放在以Integer 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天全站免登陆