Java 自定义类创建一维二维数组

这篇博客介绍了如何在Java中使用自定义类创建一维和二维数组。对于一维数组,文章讲解了将自定义类的对象存储在一维数组中的方法。在二维数组部分,通过一道具体的背包问题(P1757 - 通天之分组背包)实例,展示了如何操作自定义类对象的二维数组。

一、自定义类对象一维数组

自定义的类在外面

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}};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值