[英]How to pass a 2D Array from one class to be used in another as a parameter so that they can be sorted into 2 ArrayLists
我有一個帶有 2D 數組的 class 存儲由方法隨機生成的值。 我想使用這個二維數組來傳遞它的值,以供另一個 class 中的“GenerateGradesUranium()”方法使用。
帶有數組的 class :(據我了解,這個 Class 非常適合我希望它實現的目的)。
public class GenerateUranium
{
int[][] tray = new int[5][3];
private int grading = 0;
private Random randomGenerator;
public GenerateUranium()
{
randomGenerator = new Random();
}
public void generateSample()
{
for (int i = 0; i < tray.length; i++)
{
for (int j = 0; j < tray[i].length; j++)
{
grading = randomGenerator.nextInt(50);
tray[i][j]=grading;
}
}
printTray(tray);
}
class 和我想在其中使用二維數組的方法。(我完全迷路了)。
import java.util.ArrayList;
public class LithiumGradingUranium
{
private ArrayList highGradeUranium;
private ArrayList lowGradeUranium;
public LithiumGradingUranium()
{
}
public void generateGradesUranium() // This is the method where I want to use the Array as a parameter
{
}
因此 2D 數組在 'generateGrades()' 中用作參數,然后需要根據 > 25 (highGrade) 或 ≤ 25 (lowGrade) 的值在兩個數組列表之間進行拆分
我嘗試了多種方法來從第一個 class 獲取數組列表以在第二個中工作,但它們沒有奏效。 我看過書籍參考和視頻教程,但它們通常只處理非二維 Arrays 或在同一 class 中使用數組。 我是 Java 的新手,我已經陷入了困境,我非常感謝這方面的幫助,這樣我就可以繼續找出並完成我的程序的 rest。 不知道如何使用初始數組正在削弱我使程序按預期工作的能力。 嘗試將 2D 數組轉換為 2 個數組列表會使問題進一步復雜化。
非常感謝
我不在電腦前,自從我處理了 2d arrays 以來已經有一段時間了,但這不起作用嗎?
public void generateGrades(int[] [] tray) {
...
}
你通過2D
arrays 以類似的方式通過1D
arrays 說:
public void generateGrades(int[][] tray)
{
// Now here's some pseudo code on how to iterate the tray
for(int i = 0; i < tray.length; ++i)
{
for(int j = 0; j < tray[0].length; ++j)
{
int trayElement = tray[i][j];
if(trayElement less than 25)
{
// add it to the lower grade list
}
else
{
// add it to the higher grade list
}
}
}
}
還有一件事,當使用 generics 時,不要使用所謂的raw types
,例如
ArrayList
而是指定類型
ArrayList<Integer>
使用 java 8 個流,也可以這樣寫:
Map<Boolean, List<Integer>> result =
Arrays.stream(tray).flatMapToInt(Arrays::stream).boxed()
.collect(Collectors.groupingBy(d -> d > 25));
會給你一個java.util.HashMap
和 Boolean 鍵,如下所示:
{false=[5, 11, 25, 10, 14, 20, 15, 3, 6, 9], true=[38, 43, 38, 28, 40]}
因此,在 map 中,低等級在假密鑰下,高等級在真密鑰下,並且很容易檢索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.