一、自定义类对象一维数组
自定义的类在外面
import java.util.*;
import java.math.*;
class node
{
public int num;
public int kids;
public node()
{
num=kids=0;
}
public node(int num, int kids) {
this.num = num;
this.kids = kids;
}
}
public class Main {
public static void main(String[] args)
{
node[] t=new node[100];
for(int i=0;i<10;i++)
{
t[i]=new node(i,i);
}
}
}
二、自定义类对象的二维数组
import java.util.*;
import java.math.*;
class node
{
public int num;
public int kids;
public node()
{
num=kids=0;
}
public node(int num, int kids) {
this.num = num;
this.kids = kids;
}
}
public class Main {
public static void main(String[] args)
{
//也可以直接定义:
//node t[][]=new node[100][100];
node[][] t=new node[100][];
for(int i=0;i<10;i++)
{
t[i]=new node[100];
for(int j=0;j<10;j++)
{
t[i][j]=new node(i*j,i*j);
}
}
System.out.println(t.length);
}
}
下面是做的稍微复杂的例题,很熟悉的一道背包题目
https://www.luogu.com.cn/problem/P1757
P1757 通天之分组背包
package apple;
import java.util.Scanner;
//2021年1月28日上午10:57:58
//writer:apple
class goods
{
int w;
int p;
// int cc;
public goods()
{
w=p=0;
}
public goods(int w,int p)
{
this.w=w;
this.p=p;
}
}
public class group {
static int M;
static int N;
static int dp[]=new int[1010];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
M=scanner.nextInt();
N=scanner.nextInt();
// goods g[]=new goods[N];
// int m=scanner.nextInt();int n=scanner.nextInt();
// g[1]=new goods(m, n);
goods [][]g=new goods[N+1][N+1];
int mc=1;int hc=-1;
for(int i=1;i<=N;i++)
{
// 45 3
// 10 10 1
// 10 5 1
// 50 400 2
int a=scanner.nextInt();int b=scanner.nextInt();int c=scanner.nextInt();
if(c!=mc)
{
mc++;
hc=0;
}
else {
hc++;
}
g[mc][hc]=new goods(a, b);
}
for(int i=1;i<=mc;i++)
{
for(int j=M;j>=0;j--)
{
for(int k=0;g[i][k]!=null;k++)
{
if((j-g[i][k].w)<0) continue;
dp[j]=Math.max(dp[j], dp[j-g[i][k].w]+g[i][k].p);
}
}
}
System.out.println(dp[M]);
}
}
static int d[][]= {{1,0},{0,-1},{0,1},{-1,0}};
int d[][]= {{1,0},{0,-1},{0,1},{-1,0}};
这篇博客介绍了如何在Java中使用自定义类创建一维和二维数组。对于一维数组,文章讲解了将自定义类的对象存储在一维数组中的方法。在二维数组部分,通过一道具体的背包问题(P1757 - 通天之分组背包)实例,展示了如何操作自定义类对象的二维数组。
1万+

被折叠的 条评论
为什么被折叠?



