【问题标题】:How can I Link N elements with each other?如何将 N 个元素相互链接?
【发布时间】:2016-04-28 05:45:35
【问题描述】:

我想将 N 个元素相互链接。这意味着元素1将与元素1,元素2,元素3......元素N具有一定的价值关系。同样,元素2将与元素1,元素2,元素3......等具有价值关系. 另外我想将所有这些值存储在一个文件中并定期修改它。我更喜欢用 Java 编写代码。

什么是这个问题的完美解决方案?

请帮帮我。

【问题讨论】:

  • 一个元素如何与自己产生关系?
  • 您想在 Java 中实现某种外键 (SQL) 概念吗?链表可以给你这个功能。此外,这对我来说似乎是一项学校作业。向我们展示您所做的事情,我们将能够更好地帮助您。没有它,不要指望我们给你“完美的解决方案”。

标签: java file-handling custom-data-type


【解决方案1】:

你有一个网格。每个元素之间都有一个关系值,即有(元素个数)^2个关系值。

我会使用一个数组。然后序列化数组保存为文件,反序列化加载,编辑后再重新序列化。

这里有一些 java 代码可以保存到文件并返回:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;

public class Grid {

    public static void main(String[] args) throws Exception {

        // your data grid
        int num_elements=10;
        double[][] grid=new double[num_elements][num_elements];

        // populate the grid
        // note grid[m][n] holds the value for the relationship
        //  between element m and element n
        grid[0][0]=1.0;
        grid[0][1]=0.5;
        // etc...

        System.out.println(Arrays.deepToString(grid));

        // save the grid
        write_object(grid, "grid.data");

        // clear the grid (eg happens when you rerun your program)
        grid=null;

        // load the grid
        grid=(double[][])read_object("grid.data");
        System.out.println(Arrays.deepToString(grid));

        // do some changes
        grid[0][0]=2.0;
        grid[0][1]=1.5;
        // etc...

        // save the grid (again)
        write_object(grid, "grid.data");

        // and so on

    }


    public static void write_object(Object no, String nfilename) {
        try {
            File f=new File(nfilename);
            if (f.exists())
                f.delete();
            FileOutputStream fos=new FileOutputStream(nfilename);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(no);
            oos.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object read_object(String nfilename) {
        try {
            FileInputStream fis=new FileInputStream(nfilename);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object o=ois.readObject();
            ois.close();
            return o;
        }
        catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    相关资源
    最近更新 更多