如何将相同对象的不同实例添加到Java中的LinkedList?

时间:2014-01-03 13:35:01

标签: java linked-list

我在这里设计一个商店系统,它主要是一个媒体商店,包含视频游戏,DVD和CD等项目。我遇到的问题是我想将同一对象的不同实例(在本例中为VideoGames)存储到链表中。它似乎有效,但是当我输出List时,它只输出输入到列表中的最后一项,并重复自身以查找应该在列表中的对象数量。

我知道要查看很多代码,但任何帮助都会非常值得赞赏。

以下是addVideoGame类的代码:

import java.util.*;
import java.io.*;

public class addVideoGame extends VideoGames implements java.io.Serializable{

public static VideoGames game = new VideoGames();
public static VideoGames eGame = new VideoGames();
public static LinkedList <VideoGames> games = new LinkedList<>();
private static int vgChoice = 0;
public static int vgCount = 0;
public static int vgAmount = 0;

public static void vgMenu(){
    IBIO.output("1: Add a new videogame to the list.");
    IBIO.output("2: View the contents of the list.");
    IBIO.output("3: Save the contents of the list to the local area.");
    IBIO.output("4: Load in data from a local file.");
    IBIO.output("5: Return to the main menu.");
    vgChoice = IBIO.inputInt("Make your choice: ");

    if(vgChoice == 1){
        vgAmount = IBIO.inputInt("How many games would you like to add to the database?: ");
        for(int x = 0; x < vgAmount; x = x + 1){
        VideoGames vg = new VideoGames(); 
        vg.setTitle(IBIO.inputString("Enter the title of the game: "));
        vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
        vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
        vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
        vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
        vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));
        game = vg;
        games.add(vg);
        IBIO.output(" ");
        }
        vgMenu();
    } else if(vgChoice == 2){
        IBIO.output("Current amount of games in the list: " + games.size());
            System.out.println(Arrays.toString(games.toArray()));
        vgMenu();
    } else if(vgChoice == 3){
        try{
            FileOutputStream fileOut = new FileOutputStream("I:\\IB\\Computer Science\\TheStore\\games.txt");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(game);
            out.close();
            fileOut.close();
            IBIO.output("Data has been saved to: I:\\IB\\Computer Science\\TheStore\\games.txt");
            vgMenu();
        } catch(IOException i){
            i.printStackTrace();
        }
    } else if(vgChoice == 4){
        eGame = null;
        for(int x = 0; x < games.size(); x = x + 1){
        try{
            FileInputStream fileIn = new FileInputStream("I:\\IB\\Computer Science\\TheStore\\games.txt");
            ObjectInputStream in =  new ObjectInputStream(fileIn);
            eGame = (VideoGames) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i){
            i.printStackTrace();
            return;
        } catch(ClassNotFoundException c){
            IBIO.output("VideoGames class not found");
            c.printStackTrace();;
            return;
        }
        IBIO.output("Object Details: " + eGame.toString());
        vgMenu();
        }
    } else if(vgChoice == 5){
        IBIO.output("Returning to main menu: ");
        AccessMenus.adminMenu();
    } 
}     

}

如果有人需要它们,这里有两个用于导航程序的接口类:

public class TheStore {

static String password; //Variable created to hold and check the value of password against the correct value.
public static boolean privilege = false; //Variable created to distinguish the difference between a normal user and a user with administrator privileges.

public static void main(String[] args) {
    IBIO.output("Welcome to The Store!");
    IBIO.output("Please make sure that you enter the correct password for your given privileges.");
    password = IBIO.inputString("Enter password: ");
    if(password.equalsIgnoreCase("admin")){ //Checks the entered value against the correct value.
        privilege = true; //Sets global boolean value to true, so that admin access is granted.
        IBIO.output(" ");
        AccessMenus.adminMenu();//If password is correct, loads admin menu.
    } else if(password.equalsIgnoreCase("user")){
        privilege = false; //Keeps admin access off, so that unauthorised changes cannot be made.
        IBIO.output(" ");
        AccessMenus.userMenu();//If correct, loads user menu.
    } else {
        IBIO.output("The password is incorrect. Exiting program."); 
        System.exit(1); //If an incorrect password is entered, the program will close.
    } //close else
}//close main
}//close class TheStore

第二个:

public class AccessMenus{

    public static int choice;//Variable which will hold the value, which corresponds to an action depending on what value is entered.

    public AccessMenus(){ //Null argument constructor, to set values to 0.
        AccessMenus.choice = 0;
    }

    public AccessMenus(int c){ //Single argument constructor.
        AccessMenus.choice = c;
    }

    public static void userMenu(){
        IBIO.output("1: Sell a product.");
        IBIO.output("2: Register a customer in the Loyalty programme.");
        IBIO.output("3: Stock check.");
        IBIO.output("4: Log out.");
        IBIO.output(" ");
        IBIO.output("Please make your choice: ");
        choice = IBIO.inputInt();
        if(choice == 1){
            //Go to Sales class.
        } else if(choice == 2){
            //Go to CustomerRegister class.
        } else if(choice == 3){
            //Open the StockCheck class.
        } else if(choice == 4){
            IBIO.output("Logging out.");
            System.exit(1);
        } else {
            IBIO.output("Invalid choice. Returning to menu.");
            userMenu(); //If the value entered does not correspond to any action, the program will treat it as invalid and return to the menu.
        }//close else
    }//close userMenu

    public static void adminMenu(){
        IBIO.output("1: Sell a product.");
        IBIO.output("2: Go to the specific object menus.");
        IBIO.output("3: Stock check.");
        IBIO.output("4: Order more stock.");
        IBIO.output("5: Register a customer in the Loyalty programme.");
        IBIO.output("6: Check Loyalty members.");
        IBIO.output("7: Create databases.");
        IBIO.output("8: Log out.");
        IBIO.output(" ");
        IBIO.output("Please make your choice: ");
        choice = IBIO.inputInt();
        if(choice == 1){
            //Go to Sales class.
        } else if(choice == 2){
          int createChoice = 0;
            IBIO.output("1: Video Games.");
            IBIO.output("2: DVD.");
            IBIO.output("3: CD.");
            createChoice = IBIO.inputInt("Enter choice: ");
            if(createChoice == 1){
                addVideoGame.vgMenu();
            } else if(createChoice == 2){
                //Go to addDVD class.
            } else if(createChoice == 3){
                //Go to addCD class.
            } else {
                IBIO.output("Invalid input.");
                adminMenu();
            }
        } else if(choice == 3){
            //Go to StockCheck class.
        } else if(choice == 4){
            //Go to StockOrder class.
        } else if(choice == 5){
            //Go to CustomerRegister class.
        } else if(choice == 6){
            //Go to LoyaltyCheck class.
        } else if(choice == 7){
            //Go to DatabaseCreation class.
        } else if(choice == 8){
            IBIO.output("Logging out.");
            System.exit(1);
        } else {
            IBIO.output("Invalid input. Returning to menu.");
            adminMenu();
        } //end else
    }//close AdminMenu
}//close AccessMenus

此外,这里是VideoGames对象类,包含访问器和mutator方法以及主要字段:

public class VideoGames implements java.io.Serializable {
    //Instance variables
    public static String title;
    public static int ageRating;
    public static String genre;
    public static String publisher;
    public static String developer;
    public static int quantity;

    public VideoGames(){ //null argument constructor
        VideoGames.title = null;
        VideoGames.ageRating = 0;
        VideoGames.genre = null;
        VideoGames.publisher = null;
        VideoGames.developer = null;
        VideoGames.quantity = 0;
    }//end VideoGames null argument constructor

    public VideoGames(String t, int aG, String g, String p, String d, int q){ //6-argument constructor
      VideoGames.title = t;
      VideoGames.ageRating = aG;
      VideoGames.genre = g;
      VideoGames.publisher = p;
      VideoGames.developer = d;
      VideoGames.quantity = q;
    }//end VideoGames 6-arguement constructor

    public VideoGames(VideoGames game){
        game = new VideoGames();
    }

    @Override
    public String toString(){
        return "\nTitle: " + title + " " + "\nPublisher: " + publisher + " " + "\nDeveloper: " + developer + " " + "\nAge Rating: " + ageRating + " " + "\nGenre: " + genre + " " + "\nQuantity: " + quantity + "\n ";
    }

    //Accessor and Mutator methods
public static String getTitle(){
    return title;
    }

public static void setTitle(String t){
        title = t;
    }

public static int getAgeRating(){
        return ageRating;
    }

public static void setAgeRating(int ag){ 
        ageRating = ag;
    }

public static String getGenre(){
        return genre;
    }

public static void setGenre(String g){  
        genre = g;
    }

    public static String getPublisher(){
        return publisher;
    }

    public static void setPublisher(String p){
        publisher = p;
    }

    public static void setDeveloper(String d){
        developer = d;
}
    public static String getDeveloper(){
        return developer;
        }
    public static void setQuantity(int q){
        quantity = q;
        }

    public static int getQuantity(){
        return quantity;
        }//end method setDeveloper
}//end class VideoGames

再次,非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

我有太多代码可以正常通过,但听起来像(并且快速扫描似乎确认)您只创建一个VideoGames对象。每当您更改该对象中的任何字段时,它都会更改该单个对象中的字段。

然后将同一个VideoGames对象多次添加到列表中,但这些都是对同一对象的单独引用。

VideoGames应该被称为VideoGame,并且包含一个游戏的数据,然后您应该创建new VideoGame()并在每次向列表中添加一个游戏时进行设置。

请记住,列表只包含对象的引用,而不包含对象本身。

每个VideoGames对象就像一条街上的房子。目前你建造了一所房子,并在那栋房子的门上不断涂上不同的颜色,而不是建造多个房屋,并在每个房子的门上涂上不同的颜色。

当您添加相同的房子时,您的列表只是一个地址列表,只有4次列表重复相同的地址。

所以你在做:

在地块1中建造房屋

  1. 油漆房门蓝色
  2. 在列表中写下情节1
  3. 油漆房门绿色
  4. 再次将图1添加到列表中
  5. 油漆房门红色
  6. 再次将图1添加到列表中
  7. 现在你走到列表中,你看到三个条目 - 但是当你去看门颜色时,他们都说红色。

答案 1 :(得分:0)

您在VideoGames -class中使用静态成员。 这个值会影响所有对象,例如

 public class X {
   public static int y;X() { }
   public 
}
X x1 = new X();
x1.y = 1;
X x2 = new X();
x2.y = 2;
System.out.println("x1.y" + x1.y); // 2
System.out.println("x2.y" + x2.y); // 2

答案 2 :(得分:0)

VideoGames类的字段都是静态的。静态字段属于Class,JVM的方法区域只有一个内存空间。当你执行for循环:

VideoGames vg = new VideoGames(); 

您创建了一个VideoGames实例,但是当您执行set method时:

vg.setTitle(IBIO.inputString("Enter the title of the game: "));
   vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
   vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
   vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
   vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
   vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));

您收到的数据将设置为方法区域中的静态字段。您之前设置的值将由您设置的值覆盖。当您打印列表的值时。您将从方法区域中的静态字段中获取值。

所以,     但是当我输出List时,它只输出输入到列表中的最后一项,并重复自身以查找应该在列表中的对象数量。

希望能帮到你。 抱歉我的英语不好。