58

我听说过使用这样的二维数组:

String[][] strArr;

但是有没有办法用一个列表来做到这一点?

也许是这样的?

ArrayList<String><String> strList;

并使用这样的东西来添加它?

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

有什么办法可以做这样的事情吗?任何帮助表示赞赏。

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

4

10 回答 10

89

你会用

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();
         }
      });
   }
}
于 2012-06-02T21:49:05.643 回答
20

您可以创建一个列表,

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");

}
于 2014-07-04T06:20:39.453 回答
11

二维数组只是一个数组数组。列表的类比只是 a Listof Lists。

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

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

于 2012-06-02T21:49:58.110 回答
5

声明一个二维 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("");
}
于 2019-06-19T04:14:23.060 回答
3

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

List<List<String>> myList = new ArrayList<>();
于 2012-06-02T22:02:18.207 回答
3

事实上,二维数组是列表的列表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]
于 2015-08-06T17:33:56.327 回答
1

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

对我有用的最简单和最灵活的方法就是使用几乎“普通和旧 Java 对象”类 2D 来创建数组的每个“行”。

下面的例子有一些解释并且是可执行的(你可以复制粘贴它,但记得检查包名):

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)
于 2016-05-04T00:37:39.047 回答
0

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

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");
    }
}
于 2015-11-02T05:29:29.367 回答
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();
        }
    }
}
于 2018-06-25T03:26:34.043 回答
0
ArrayList<ArrayList<String>> ar = new ArrayList<>();
ArrayList<String> arr = new ArrayList<>();
arr.add("data1");
arr.add("data2");
ar.add(arr);
System.out.println(ar.get(0).get(0));
// Output data1

这么简单

于 2021-10-19T08:54:23.850 回答