Привет, я пытаюсь понять 2d массивов в java. В основном я пытаюсь взять сотовые данные из каждой страны и отображать их так:
Страна 1983 1984 1985 США 10 20 40 Мексика 2 3 1
В основном принимает строку, представляющую страну и int, представляющую фактический номер статуса. Я беру статистику с 1983 по 1985 год.
Мое предположение не уверен, что я прав: создайте объект из массива 2d. 1 для строки, 2nd для int. но теряются при реализации и не знают, правильно ли это сделать, или кто-нибудь может помочь и сделать какое-либо предложение будет благодарен.
Любое предложение будет полезно.
ниже моя реализация кода кода:
public class CellularData
{
private String []country;
private double []stats;
CellularData [][]array;
private int year;
public CellularData(int rows, int column, int year){
this.country = new String[rows];
this.stats = new double[column];
array = new CellularData[country.length][stats.length];
this.year = year;
}
public void insert(String country, double []num){
//this is where I'm having the problem.
//don't think i am right.
for(int i=0;i<array.length;i++)
{
array[i] = country;
for(int j =0;j<array[i].length;j++)
{
array[i][j] = num[j];
}
}
}
//Below is my Test class
public class TestCellularData(){
public static void main(String []args){
final double[] canada = {0,0,0.05,0.23,0.37,0.75,1.26};
final double[] mexico = {0,0,0,0,0,0,0.01};
final double[] usa = {0,0,0.14,0.28,0.5,0.83,1.39};
int startingYear = 1983;
CellularData datatable;
int numRows = 3;
int numColumns = canada.length;
datatable = new CellularData(numRows, numColumns, startingYear);
datatable.insert("canada", canadaPartial);
datatable.insert("mexico", mexicoPartial);
datatable.insert("usa", usaPartial);
System.out.println(datatable);
У вашего предоставленного исходного кода есть некоторые небольшие проблемы. Прежде всего, вам придется использовать массив Object
для хранения String
и Double
в нем. Массив CellularData не может этого сделать.
Второй проблемой был ваш метод insert
. Он записывал данные в каждую строку массива и удалял уже сохраненные данные таким образом. Чтобы исправить это, вам придется сначала искать первую пустую строку.
Дополнительную информацию см. В следующем коде и комментариях.
public class CellularData {
private Object[][] array; // <- use Object instead of CellularData
public CellularData(int rows, int column, int year) {
array = new Object[rows + 1][column + 1]; // <- +1 for the heading line and the country name column
// write head line to array
array[0][0] = "Country";
for (int i = 1; i <= column; i++) {
array[0][i] = year++;
}
}
public void insert(String country, double[] num) {
for (int i = 0; i < array.length; i++) {
if (array[i][0] == null) { // <- search for an empty row to insert the data there
insert(country, num, i);
break;
}
}
}
private void insert(String country, double[] num, int row) {
array[row][0] = country; // <- write the country to the first column
for (int j = 1; j < array[row].length; j++) { // <- data starts at the second column
array[row][j] = num[j - 1]; // <- -1 because the num array is one column shorter than 'array' (due to the country name column in 'array')
}
}
public static void main(String[] args) {
final double[] canada = { 0, 0, 0.05, 0.23, 0.37, 0.75, 1.26 };
final double[] mexico = { 0, 0, 0, 0, 0, 0, 0.01 };
final double[] usa = { 0, 0, 0.14, 0.28, 0.5, 0.83, 1.39 };
int startingYear = 1983;
CellularData datatable;
int numRows = 3;
int numColumns = canada.length;
datatable = new CellularData(numRows, numColumns, startingYear);
datatable.insert("canada", canada);
datatable.insert("mexico", mexico);
datatable.insert("usa", usa);
// print array content
for (Object[] row : datatable.array) {
for (Object cell : row) {
System.out.print(cell + "\t");
}
System.out.println();
}
}
}
Метод тестирования печатает
Country 1983 1984 1985 1986 1987 1988 1989
canada 0.0 0.0 0.05 0.23 0.37 0.75 1.26
mexico 0.0 0.0 0.0 0.0 0.0 0.0 0.01
usa 0.0 0.0 0.14 0.28 0.5 0.83 1.39
Object
, потому что это родительский класс любого другого класса. CellularData
другой стороны, CellularData
не имеет ничего общего ни со String
ни с Double
. Таким образом, JVM не может знать, как привести / преобразовать String
в CellularData
или Double
в CellularData
.
вы можете использовать массив класса Object, например
Object[][] ob = {{"One", 1},{"Two", 2}, {"Three", 3}};
Примечание. Чтобы получить доступ к значениям, которые вам нужно будет присвоить значениям требуемому типу (строка не требуется явно указывать)
ИЛИ
вы должны использовать HashMap Like
HashMap<String, Integer> map = new HashMap<>();
используйте метод put(String, Integer)
для вставки значений и get(index)
для доступа к значениям
Примечание. Вы не можете хранить примитивные типы в HashMap
но вам нужно будет использовать Integer
вместо int, а затем вы можете изменить его на int.
Вместо этого вы можете создать объект, который инкапсулирует эти точки данных и вместо этого сохранит это в одномерном массиве. Вы даже можете сделать их сортируемыми к году, Comparable
.
public class CountryData implements Comparable<CountryData> {
private final Integer year;
private final String country;
private final Integer dataPoint;
public CountryData(Integer year, String country, Integer dataPoint) {
this.year = year;
this.country = country;
this.dataPoint = dataPoint;
}
// presume getters defined
public int compareTo(CountryData other) {
return year.compareTo(other.getYear());
}
}
Кроме того, если вы чувствуете себя особенно предприимчивым, вы можете экспериментировать с Guava Table.
Table<Integer, String, Integer> countryData = HashBasedTable.create();
countryData.put(1983, "USA", 10);
// and so forth
Object
для своего двумерного массива, и вам нужно было бы помещать String
и Integer
внутри массива в определенных местах.
Map<String, Map<Integer, Integer>>
.