首页 > 解决方案 > 如何在java中制作嵌套结构数组?

问题描述

如何在java中制作这样的数组结构?以及如何在 Main Class 中启动它?

struct Channel{

    char email[100];
    char password[100];
    char channelName[100];
    char subscriber[][100];
    int numberOfSubscriber;
    int numberOfVideos;

    struct Video{
         String videoId ;
         char videoName ;
         char videoDuration ;
         char videoTag ;
    }video[100];

}channel[100];
// i need to make it like this ( channel[i].video[j].*** )

标签: javaarraysclassstructnested

解决方案


您在 java 中创建类。

java.util.List您可以使用它来动态添加或删除元素,而不是在这里使用数组。

这是一个例子。您可以通过添加构造函数、将字段设为私有并添加公共 getter 和 setter 来控制数据流来改进这一点。

import java.util.ArrayList;
import java.util.List;

class Video {
    String videoId;
    String videoName;
    String videoDuration;
    String videoTag;
}

class Channel {
    String email;
    String password;
    String channelName;
    List<String> subscriber = new ArrayList<>();
    List<Video> videos = new ArrayList<>();

    public int numberOfSubscriber() {
        return subscriber.size();
    }
    public int numberOfVideos() {
        return videos.size();
    }
}

public class Main {
    public static void main(String[] args) {
        // create a new channel
        Channel channel = new Channel();

        // modify some variables
        channel.email = "example@example.com";
        channel.subscriber.add("subscriber 1");

        // create a new video
        Video video = new Video();
        video.videoName = "this is a video";

        // add video to channel
        channel.videos.add(video);

        // get number of videos
        System.out.println(channel.numberOfVideos());
    }
}

推荐阅读