二维数组列表

时间:2012-06-02 21:48:19

标签: java

我听说过像这样使用2D数组:

String[][] strArr;

但有没有办法用清单做到这一点?

也许是这样的?

ArrayList<String><String> strList;

使用这样的东西添加到它?

strList.add("hey", "hey");

任何做这样的事情?任何帮助表示赞赏。

如果有的话会很好,因为我正在将字符串成对地放入两个不同的ArrayList中。

9 个答案:

答案 0 :(得分:71)

你会用

List<List<String>> listOfLists = new ArrayList<List<String>>();

然后当您需要添加新的“行”时,您需要添加列表:

listOfLists.add(new ArrayList<String>());

当我想在GUI中保存对Point的几个列表的引用时,我已经使用了这个,所以我可以绘制多条曲线。效果很好。

例如:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class DrawStuff extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final Color POINTS_COLOR = Color.red;
   private static final Color CURRENT_POINTS_COLOR = Color.blue;
   private static final Stroke STROKE = new BasicStroke(4f);
   private List<List<Point>> pointsList = new ArrayList<List<Point>>();
   private List<Point> currentPointList = null;

   public DrawStuff() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
            RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setStroke(STROKE);
      g.setColor(POINTS_COLOR);
      for (List<Point> pointList : pointsList) {
         if (pointList.size() > 1) {
            Point p1 = pointList.get(0);
            for (int i = 1; i < pointList.size(); i++) {
               Point p2 = pointList.get(i);
               int x1 = p1.x;
               int y1 = p1.y;
               int x2 = p2.x;
               int y2 = p2.y;
               g.drawLine(x1, y1, x2, y2);
               p1 = p2;
            }
         }
      }
      g.setColor(CURRENT_POINTS_COLOR);
      if (currentPointList != null && currentPointList.size() > 1) {
         Point p1 = currentPointList.get(0);
         for (int i = 1; i < currentPointList.size(); i++) {
            Point p2 = currentPointList.get(i);
            int x1 = p1.x;
            int y1 = p1.y;
            int x2 = p2.x;
            int y2 = p2.y;
            g.drawLine(x1, y1, x2, y2);
            p1 = p2;
         }
      }
   }

   private class MyMouseAdapter extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent mEvt) {
         currentPointList = new ArrayList<Point>();
         currentPointList.add(mEvt.getPoint());
         repaint();
      }

      @Override
      public void mouseDragged(MouseEvent mEvt) {
         currentPointList.add(mEvt.getPoint());
         repaint();
      }

      @Override
      public void mouseReleased(MouseEvent mEvt) {
         currentPointList.add(mEvt.getPoint());
         pointsList.add(currentPointList);
         currentPointList = null;
         repaint();
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("DrawStuff");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new DrawStuff());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

答案 1 :(得分:14)

您可以创建一个列表

ArrayList<String[]> outerArr = new ArrayList<String[]>(); 

并像这样添加其他列表:

String[] myString1= {"hey","hey","hey","hey"};  
outerArr .add(myString1);
String[] myString2= {"you","you","you","you"};
outerArr .add(myString2);

现在,您可以使用下面的双循环显示所有列表中的所有内容

for(int i=0;i<outerArr.size();i++){

   String[] myString= new String[4]; 
   myString=outerArr.get(i);
   for(int j=0;j<myString.length;j++){
      System.out.print(myString[j]); 
   }
   System.out.print("\n");

}

答案 2 :(得分:10)

2d数组只是一个数组数组。列表的模拟只是List的{​​{1}}。

List

我承认,这不是一个很好的解决方案,特别是如果你选择3维或更多维度的结构。

答案 3 :(得分:3)

如果您的平台矩阵支持Java 7,那么您可以使用如下

List<List<String>> myList = new ArrayList<>();

答案 4 :(得分:2)

事实上,2维数组是X列表的列表,其中X是从典型数据结构到用户定义数据结构的数据结构之一。作为以下快照代码,我逐行添加到数组triangle中。为了创建每一行,我使用方法add手动添加元素或使用方法asList从数据带创建列表。

package algorithms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RunDemo {

/**
 * @param args
 */
public static void main(String[] args) {
    // Get n
    List<List<Integer>> triangle = new ArrayList<List<Integer>>();

    List<Integer> row1 = new ArrayList<Integer>(1);
    row1.add(2);
    triangle.add(row1);

    List<Integer> row2 = new ArrayList<Integer>(2);
    row2.add(3);row2.add(4);
    triangle.add(row2);

    triangle.add(Arrays.asList(6,5,7));
    triangle.add(Arrays.asList(4,1,8,3));

    System.out.println("Size = "+ triangle.size());
    for (int i=0; i<triangle.size();i++)
        System.out.println(triangle.get(i));

}
}

运行样本,它会生成输出:

Size = 4
[2]
[3, 4]
[6, 5, 7]
[4, 1, 8, 3]

答案 5 :(得分:1)

我知道这是一个很好的答案的老问题,但我相信我可以加2美分。

对我来说最简单,最灵活的方法就是使用几乎&#34;普通和旧Java对象&#34; class2D创建每个&#34; row&#34;你的阵列。

以下示例有一些解释并且是可执行的(您可以复制并粘贴它,但请记住检查包名称):

package my2darraylist;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;

public class My2DArrayList
{
    public static void main(String[] args)
    {
        // This is your "2D" ArrayList
        // 
        List<Box> boxes = new ArrayList<>();

        // Add your stuff
        //
        Box stuff = new Box();
        stuff.setAString( "This is my stuff");
        stuff.addString("My Stuff 01");
        stuff.addInteger( 1 );
        boxes.add( stuff );

        // Add other stuff
        //
        Box otherStuff = new Box();
        otherStuff.setAString( "This is my other stuff");
        otherStuff.addString("My Other Stuff 01");
        otherStuff.addInteger( 1 );
        otherStuff.addString("My Other Stuff 02");
        otherStuff.addInteger( 2 );
        boxes.add( otherStuff );

        // List the whole thing
        for ( Box box : boxes)
        {
            System.out.println( box.getAString() );
            System.out.println( box.getMyStrings().size() );
            System.out.println( box.getMyIntegers().size() );
        }
    }

}

class Box
{
    // Each attribute is a "Column" in you array
    //    
    private String aString;
    private List<String> myStrings = new ArrayList<>() ;
    private List<Integer> myIntegers = new ArrayList<>();
    // Use your imagination...
    //
    private JPanel jpanel;

    public void addString( String s )
    {
        myStrings.add( s );
    }

    public void addInteger( int i )
    {
        myIntegers.add( i );
    }

    // Getters & Setters

    public String getAString()
    {
        return aString;
    }

    public void setAString(String aString)
    {
        this.aString = aString;
    }

    public List<String> getMyStrings()
    {
        return myStrings;
    }

    public void setMyStrings(List<String> myStrings)
    {
        this.myStrings = myStrings;
    }

    public List<Integer> getMyIntegers()
    {
        return myIntegers;
    }

    public void setMyIntegers(List<Integer> myIntegers)
    {
        this.myIntegers = myIntegers;
    }

    public JPanel getJpanel()
    {
        return jpanel;
    }

    public void setJpanel(JPanel jpanel)
    {
        this.jpanel = jpanel;
    }
}

更新 - 为了回答@Mohammed Akhtar Zuberi提出的问题,我已经创建了该程序的简化版本,以便更容易地显示结果。

import java.util.ArrayList;

public class My2DArrayListSimplified
{

    public static void main(String[] args)
    {
        ArrayList<Row> rows = new ArrayList<>();
        Row row;
        // Insert the columns for each row
        //             First Name, Last Name, Age
        row = new Row("John",      "Doe",     30);
        rows.add(row);
        row = new Row("Jane",      "Doe",     29);
        rows.add(row);
        row = new Row("Mary",      "Doe",      1);
        rows.add(row);

        // Show the Array
        //
        System.out.println("First\t Last\tAge");
        System.out.println("----------------------");
        for (Row printRow : rows)
        {
            System.out.println(
                    printRow.getFirstName() + "\t " +
                    printRow.getLastName() + "\t" +
                    printRow.getAge());

        }
    }

}

class Row
{

    // REMEMBER: each attribute is a column
    //
    private final String firstName;
    private final String lastName;
    private final int age;

    public Row(String firstName, String lastName, int age)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public int getAge()
    {
        return age;
    }

}

上面的代码产生以下结果(我在NetBeans上运行它):

run:
First    Last   Age
----------------------
John     Doe    30
Jane     Doe    29
Mary     Doe    1
BUILD SUCCESSFUL (total time: 0 seconds)

答案 6 :(得分:0)

以下是使用ArrayList对象制作和打印2D多维数组的方法。

import java.util.ArrayList;

public class TwoD_ArrayListExample {
    static public ArrayList<ArrayList<String>> gameBoard = new ArrayList<ArrayList<String>>();

    public static void main(String[] args) {
        insertObjects();
        printTable(gameBoard);
    }

    public static void insertObjects() {
        for (int rowNum = 0; rowNum != 8; rowNum++) {
            ArrayList<String> oneRow = new ArrayList<String>();
            gameBoard.add(rowNum, oneRow);

            for (int columnNum = 0; columnNum != 8; columnNum++) {
                String description= "Description of Objects: row= "+ rowNum + ", column= "+ columnNum;
                    oneRow.add(columnNum, description);
            }
        }
    }

    // The printTable method prints the table to the console
    private static void printTable(ArrayList<ArrayList<String>> table) {
        for (int row = 0; row != 8; row++) {
            for (int col = 0; col != 8; col++) {
                System.out.println("Printing:               row= "+ row+ ", column= "+ col);
                System.out.println(table.get(row).get(col).toString());
            }
        }
        System.out.println("\n");
    }
}

答案 7 :(得分:0)

for (Project project : listOfLists) {
    String nama_project = project.getNama_project();
    if (project.getModelproject().size() > 1) {
        for (int i = 1; i < project.getModelproject().size(); i++) {
            DataModel model = project.getModelproject().get(i);
            int id_laporan = model.getId();
            String detail_pekerjaan = model.getAlamat();
        }
    }
}

答案 8 :(得分:0)

声明一个二维ArrayList:

ArrayList<ArrayList<String>> rows = new ArrayList<String>();

ArrayList<ArrayList<String>> rows = new ArrayList<>();

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(); 

以上所有都是二维ArrayList的有效声明!

现在,声明一维ArrayList:

ArrayList<String> row = new ArrayList<>();

在二维ArrayList中插入值:

for(int i=0; i<5; i++){
    ArrayList<String> row = new ArrayList<>();
    for(int j=0; j<5; j++){
        row.add("Add values here"); 
    }
    rows.add(row); 
}

从二维ArrayList获取值:

for(int i=0; i<5; i++){
    for(int j=0; j<5; j++){
        System.out.print(rows.get(i).get(j)+" ");
     }
     System.out.println("");
}