如何搜索特定字段的对象链接列表?

时间:2018-05-13 18:53:34

标签: java linked-list

我正在编写一个程序,将我的班级“TeamRecord”的对象存储到一个链表中。我在使搜索方法工作时遇到问题。下面的代码适用于只包含字符串的链表,但由于这是TeamRecord对象的链接列表,我需要弄清楚如何仅查看团队名称字段。

调用搜索方法:

case 5:     
    System.out.println("Enter team name to search: ");
    String input = console.next();

    if(teams.search(input))
        System.out.println(input + " is a team.");
    else
    System.out.println(input + " is not a team.");

    break;

我收到错误,因为String输入无法转换为TeamRecord

搜索方法:

public boolean search(E element) {
  if(isEmpty())
     return false;
  //create a new node for the element

  Node<E> temp = new Node<E>(element, null);
  temp = head;

  while(temp != null)
  {
     if(temp.getElement().equals(element))
        return true;

     temp = temp.getNext();
  }

  return false; 
}

我试过了:

if(teams.getTeamName().search(input))

这不起作用,因为“teams”是LinkedList的名称所以我实际上并没有查看单个对象。我真的不确定如何解决这个问题。任何帮助将不胜感激

我会在这里发布其余的代码,以防上述情况不够:

public class TeamRecord implements Comparable<TeamRecord>{

private String teamName;
private int totalWin;
private int totalLoss;

public TeamRecord() {
}

public TeamRecord(String teamName, int totalWin, int totalLoss) {
    this.teamName = teamName;
    this.totalWin = totalWin;
    this.totalLoss = totalLoss;
}

public String getTeamName() {
    return teamName;
}

public void setTeamName(String teamName) {
    this.teamName = teamName;
}

public int getTotalWin() {
    return totalWin;
}

public void setTotalWin(int totalWin) {
    this.totalWin = totalWin;
}

public int getTotalLoss() {
    return totalLoss;
}

public void setTotalLoss(int totalLoss) {
    this.totalLoss = totalLoss;
}

public int compareTo(TeamRecord T) {
    return this.teamName.compareTo(T.teamName);

}
@Override
public String toString() {
    return "\n\nTeam Name: " + teamName + "\nTotal Wins: " + totalWin + 
            "\nTotal Losses: " + totalLoss;
}



}

链接列表:

public class MyLinkedList<E> {

   //data members
   private Node<E> head;
   private Node<E> tail;

   int size;

      //contructor
   public MyLinkedList(){
      head = null;
      tail = null;
      size = 0;
   }

   public boolean isEmpty(){
      if(head == null)
         return true;

      return false;
   }

   public int size(){
      return size;
   }

   public void addFirst(E element){

      //create a new node for the element

      Node<E> temp = new Node(element, null);

      //if the list is empty
      if(isEmpty()){
         head = temp;
      }
      else{
         //temp's next = head
         temp.setNext(head);
         head = temp;

      }
      size++;
   } 

   public E removeFirst() throws EmptyListException {

      if(isEmpty()) 
         throw new EmptyListException("This list is empty.");

      Node<E> temp = head;

         //move head to head next
      head = head.getNext();

      E result = temp.getElement();

      temp.setNext(null);
      temp = null;

      size--;

      return result;

   }
   public void addLast(E element) {

      //create a new node for the element

      Node<E> temp = new Node<E>(element, null);

      if(head != null)
      {
         Node<E> tail = head;
         while(tail.getNext() != null)
         {
            tail = tail.getNext();
         }
         tail.setNext(temp);
      }
      else
         head = temp;

      size++;

   }

   public boolean search(E element) {
      if(isEmpty())
         return false;
      //create a new node for the element

      Node<E> temp = new Node<E>(element, null);
      temp = head;

      while(temp != null)
      {
         if(temp.getElement().equals(element))
            return true;

         temp = temp.getNext();
      }

      return false; 
   }

   public String traverse(){

      if(isEmpty())
         return "Empty list";

      String result = "Head --->";

      int i = size;

      Node<E> temp = head;

      while(i > 0){
         result += temp.getElement();
         temp = temp.getNext();
         i--;
      }
      return result;
   }

}//end of class

节点类:

 class Node<E> {

   //data members
   private E element;
   private Node<E> next;

   //constructors
   public Node() {
      this(null, null);
   }

   public Node(E element, Node<E> next) {
      this.element = element;
      this.next = next;
   }

   //setters and getters
   public void setElement(E element) {
      this.element = element;
   }

   public void setNext(Node<E> next) {
      this.next = next;
   }

   public E getElement() {
      return element;
   }

   public Node<E> getNext() {
      return next;
   }

}

客户端:

public class TeamRecordClient {

   static Scanner console = new Scanner(System.in);

   public static int main(String [] args) {

      MyLinkedList<TeamRecord> teams = new MyLinkedList();


      boolean flag = true;
      int userCommand;
      while (flag) {
         showMenu();

         userCommand = console.nextInt();

         switch (userCommand) {
              //addFirst
            case 1:
               System.out.println("Enter Team Name: ");
               String name = console.next();

               System.out.println("Enter Total Wins: ");
               int totalWins = console.nextInt();

               System.out.println("Enter Total Losses: ");
               int totalLosses = console.nextInt();

               teams.addFirst(new TeamRecord(name, totalWins, totalLosses));


               break;
              //removeFirst
            case 2:
               try{
                  TeamRecord result = teams.removeFirst();

                  System.out.println("Removed Team: " + teams.toString());
               }
               catch(EmptyListException e) {
                  System.out.println(e.toString());
               }
               break;
              //addLast
            case 3:
               System.out.println("Enter Team Name: ");
               String name1 = console.next();

               System.out.println("Enter Total Wins: ");
               int totalWins1 = console.nextInt();

               System.out.println("Enter Total Losses: ");
               int totalLosses1 = console.nextInt();

               teams.addLast(new TeamRecord(name1, totalWins1, totalLosses1));

               break;
              //traverse
            case 4:
               System.out.println(teams.traverse());

               break;
              //search for a element
            case 5:     
               System.out.println("Enter team name to search: ");
               String input = console.next();

               if(teams.search(input))
                  System.out.println(input + " is a team.");
               else
                  System.out.println(input + " is not a team.");

               break;

            case 0:
               flag = false;
               break;
            default:
         }
      }//end main
   }     
   private static void showMenu() {
      System.out.print("\n\n"
                + "\n1 - Add First"
                + "\n2 - Remove First"
                + "\n3 - Add Last"
                + "\n4 - Traverse"
                + "\n5 - Search"
                + "\n6 - Selection Sort(Team Name)"
                + "\n7 - Quick Sort(Total Wins)"
                + "\n0 - Exit "
                + "\nEnter a command: ");
   }

}//end of class

1 个答案:

答案 0 :(得分:0)

我建议您修改search()方法以取代谓词:

public boolean search(Predicate<? super E> predicate) {
    Node<E> temp = head;
    while (temp != null) {
        if (predicate.test(temp.getElement()))
            return true;
       temp = temp.getNext();
    }
    return false; 
}

然后,您可以为搜索指定任何Predicate

if (teams.search(e -> e.getTeamName().equals(input))
    System.out.println(input + " is a team.");
else
    System.out.println(input + " is not a team.");