java 二维数组和字符串相互转化?

2024-11-29 17:06:18
推荐回答(2个)
回答1:

package test;

public class ArrayToStringTest {
public static void main(String[] args) {
int[][] array = new int[4][4];
int count = 0;
ArrayToStringTest test = new ArrayToStringTest();

// 赋值一链携蚂个int[][]
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = count;
++count;
}
}

//棚埋 获取row,col
int row = test.getRow(array);
int col = test.getCol(array);

// 转为String
String str = test.convertToString(array, row, col);
System.out.println(str); /隐源/ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,

//转为int[][]
int[][] arrayConvert = new int[row][col];
arrayConvert = test.convertToArray(str, row, col);
}

public int getRow(int[][] array) {
int row = 0;
if (array != null) {
row = array.length; // 行
}
return row;
}

public int getCol(int[][] array) {
int col = 0;
if (array != null) {
col = array[0].length; // 列
}
return col;
}

public String convertToString(int[][] array, int row, int col) {
String str = "";
String tempStr = null;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
tempStr = String.valueOf(array[i][j]);
str = str + tempStr + ",";
}
}
return str;
}

public int[][] convertToArray(String str, int row, int col){
int[][] arrayConvert = new int[row][col];
int count = 0;
String[] strArray = str.split(",");
for(int i = 0 ; i < row ; i ++){
for(int j = 0 ; j < col ; j ++){
arrayConvert[i][j] = Integer.parseInt(strArray[count]);
++ count ;
}
}
return arrayConvert;
}
}

回答2:

学厅裂了集合,感觉数组就可以淘汰了。~~~

你的目的是将2维数组序列化,是吧。
好了,经过研究,2维数组是可以序列化的。
import java.io.Serializable;

public class Demo implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int number;
public Demo(){

}
public Demo(String name,int number){
this.name= name;
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MyMain {

public static void main(String args[]){
Demo[][] demos = {
{new Demo("张三",1),new Demo("李四",2)},
{new Demo("张五",3),new Demo("孙6"中山,4)}

};
//Demo d = new Demo("张三",1);
//Array a = new Array
ObjectOutputStream os;
try {
os = new ObjectOutputStream(new FileOutputStream("abc.txt"));
os.writeObject(demos);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//上面是保存
//下面扮培闭是读取
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream("abc.txt"));
Demo[][] demos1 = (Demo[][]) input.readObject();
System.out.println(demos1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("over");
}
}