Java LinkedList accessing 2nd element
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:
I suggest you rename your
List
class toPerson
, as object of that type clearly does not represent lists.name
andlastName
will not be elements of the list. They are arguments to the constructor of theList
(readPerson
) class.You have no fields in your
List
, so you can't dothis.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()
精彩评论