Java creates an array of custom classes

Source: Internet
Author: User

Today, the smallest spanning tree that is learning graph theory, has been thinking of using adjacency Matrix or association matrix to represent the graph, but found that there will be a lot of space wasted. So I'm going to customize an edge class that contains the weights, the associated endpoint 1, the endpoint 2, and the representation letters of the graph. Found I want to create 11 edges, bian[] = new bian[11] when; Then call BIAN[0].V has been reported null pointer exception, also Baidu, found some small partners and I encountered the same problem. So I thought about it and found that in Java, the array holds the object of this type, everything objects. I define bian[] when it should be stored bian[] type first. For example, the following programs

Import Java.util.Scanner;

Class bian{
int V; Weighted value of the edge
int guanlian[] = new int[2];//each edge is associated with 2 points
Char Xuhao;
}

public class Test {
public static void Main (string[] args) {
System.out.println ("Please enter this figure has several sides:"); Representation of graphs with associative matrices
Scanner SCN = new Scanner (system.in);
int n = scn.nextint ();
Bian bian[] = new Bian[n]; With so many edges initialized, you start typing
for (int i=0;i<n;i++) {
Bian[i] = new Bian (); To create this object, put it in this array before you can use the
BIAN[I].V = Scn.nextint ();
Bian[i].guanlian[0] = Scn.nextint ();
BIAN[I].GUANLIAN[1] = Scn.nextint ();
Bian[i].xuhao = (char) (' a ' +i);
}
}
}

We need to remember that later.

Java creates an array of custom classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.