开发者

Java LinkedList accessing 2nd element

开发者 https://www.devze.com 2023-04-05 06:05 出处:网络
I have created a linkedlist which stores two elements. Can someone tell me how to access the second element. In this case, the lastName

I have created a linkedlist which stores two elements. Can someone tell me how to access the second element. In this case, the lastName

This is what I came up with so far.

public class Bank
{
  private LinkedList<List> words = new LinkedList<List>();
  public void startup()
   {
     words.ad开发者_StackOverflowd(new List("Fred","Cool"));
   }

This is my list class

public class List
{
   public List(String name, String lastName)
   {
     this.name = name;
     this.lastName = lastName;
 }


You have a number of problems in your code:

  1. I suggest you rename your List class to Person, as object of that type clearly does not represent lists.

  2. name and lastName will not be elements of the list. They are arguments to the constructor of the List (read Person) class.

  3. You have no fields in your List, so you can't do

    this.name = name;
    this.lastName = lastName;
    

To access the second element in the words list, you do

words.get(1);   // access second element (indecies are 0-based)

However, since you've only added one element you won't be able to use the above expression.


Here's a complete example to get you on the right track:

import java.util.LinkedList;

class Bank {
    private LinkedList<Person> persons = new LinkedList<Person>();

    public void startup() {
        persons.add(new Person("Fred", "Cool"));
    }

    public LinkedList<Person> getPersonList() {
        return persons;
    }
}

class Person {
    String name, lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }
}

class Test {
    public static void main(String[] args) {
        Bank bank = new Bank();
        bank.startup();

        String lastNameOfFirstPerson = bank.getPersonList().get(0).lastName;
        System.out.println(lastNameOfFirstPerson); // prints "Cool"
    }
}


words.get(index).lastName;

This is assuming that the field is accessable.


Accessing linked list element by index can be very inefficient. Try using ListIterator<E> LinkedList#listIterator()

0

精彩评论

暂无评论...
验证码 换一张
取 消