1

For this example I have an array:

String[] books = new String[x];

I would like to store the id and title in each location:

books[0]=>id:0, title:"book title1"
books[0]=>id:1, title:"book title2"
books[0]=>id:2, title:"book title3"
books[0]=>id:3, title:"book title4"

I want to store the id since it may change. I'm getting the id and title from a database. Getting the info isn't the issue. I want to store it this way so in my other functions this returns to I can use something like:

btn.setText(regions[i].title)

Any suggestion on how to handle this would be great.

4
  • 1
    Why don't you create a Book class, that has id and title as class members? Commented Nov 27, 2013 at 4:22
  • you can use a hash map where id is the key Commented Nov 27, 2013 at 4:23
  • 1
    Use can use an ArrayList of Pair<Integer,String> objects.. Commented Nov 27, 2013 at 4:26
  • you would want to brush through OOP concepts AND Collections and figure out an approach for it is pretty straight forward. Commented Nov 27, 2013 at 4:31

3 Answers 3

3

Do one thing, first create a bean class like BookBean. Under this declare two variables ID and Title. and declare getters and setters (If u are using eclipse u can easily do this by (Source -> generate getters and setters.. option) and then declare a ArrayList to store BookBean vale as of follow.

 ArrayList<BookBean> bookArrayList=new ArrayList<BookBean>();

   for(int i=0;i<=urSize;i++)
   {
    // create a object for BookBean 
    BookBean book =new BookBean();
    book.setID("what ever");
    book.setTitle("what ever");
    bookArrayList.ass(book)
    }
Sign up to request clarification or add additional context in comments.

Comments

2

It is better to use Arraylist with custom class.

see this

class Book
{
   String id,title;

   /* Cunstructor to store data */
   public Book(String id,String title) 
   {
       this.id = id;
       this.title = title;
   }
}

//declare arraylist
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add("1","book1");
bookList.add("2","book2");
bookList.add("3","book3");
bookList.add("4","book4");

btn.setText(bookList.get(i).title)

1 Comment

you meant: bookList.add(new Book("1","book1"));
1

I think you have several options

  • Use a HashMap where you can use your id as key and value title

  • Define a class and keep id and title as attributes , define get and set methods.

Keep the objects of the class in a ArrayList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.