HashMap of a and ArrayList of a Class - java

I am new to Java and I am trying to build up a set of tuples like this:
Slegs = {<1,2,500> , <2,5,400>, <5,7,850>, <2,3,450>} and etc.
Then, to define other arrays like:
int u [Slegs][G];
for instance :
u[<1,2,500>][1] = 80
u[<2,5,400>][1] = 80
u[<1,2,500>][2] = 65
u[<2,5,400>][2] = 130
and etc.
For this, I have coded as follows:
public class Model {
public static int Y = 7;
public static int K = 42;
public static int G = 3;
class Sleg {
public int i;
public int j;
public double l;
List<Sleg> Slegs = new ArrayList<Sleg>();
Map <Integer, Sleg> slTup = new HAshMap<Integer, Sleg>();
int[][] u = new int [key][G]; /* I want to define and use a key here*/
}
My problem is that I don't know how to add those tuples into the slTup a for loop, and how to assign a key to them so that I can use the key to define the u[key][G]; As well, how to assert / define that i and j are in Y and i !=j in each tuple <i,j,l>;
I would really appreciate if you could instantiate and printout u[key][g], using the given theoretical data above.

I have some code with these following as a requirement. Not sure what this application is all about, but here is my attempt to answer the questions posed:
Problem:
how to add those tuples into the slTup in a for loop
how to assign a key to them so that I can use the key to define the u[key][G];
could instantiate and printout u[key][g]
want to have a map of integers and Slegs like <1,<1,2,500>> and <2,<2,5,400>>, where the integer is the key and I can then use it in: u[Key][G]
how to assert / define that i and j are in Y and i !=j in each tuple .
Note that its not clear about what it means by "assert i and j are in Y". But, i != j can be asserted by throwing a run time exception (see Sleg class code constructor).
The program with possible answers:
import java.util.*;
public class SlegProgram {
private static int key;
public static void main(String [] args) {
// Create some Slegs
List<Sleg> slegs = Arrays.asList(new Sleg(1,2,500), new Sleg(2,5,400), new Sleg(1,2,500), new Sleg(2,5,400));
System.out.println(slegs);
// Create a Sleg Map with keys
Map <Integer, Sleg> slegMap = new HashMap<>();
for (Sleg sleg : slegs) {
slegMap.put(++key, sleg);
}
System.out.println(slegMap);
// Instantiate and printout u [key][G]
for (Map.Entry<Integer, Sleg> entry : slegMap.entrySet()) {
int [][] u = new int [entry.getKey()][Model.G];
System.out.println(Arrays.deepToString(u)); // prints array with initial values: 0
assignValuesToU(u);
}
// Assert i != j in each Sleg
Sleg illegal = new Sleg(1, 1, 90); // This will throw an exception as i and j are equal
}
private static void assignValuesToU(int [][] u) {
for (int i = 0; i < u.length; i++) {
for (int j = 0; j < u[i].length; j++) {
u [i][j] = 80; // 80 or whatever it needs to be
}
}
System.out.println(Arrays.deepToString(u)); // prints array with assigned values
}
}
class Sleg {
private int i;
private int j;
private int k;
public Sleg(int i, int j, int k) {
if (i == j) {
throw new IllegalArgumentException("Invalid sleg parameters: " + Integer.toString(i));
}
this.i = i;
this.j = j;
this.k = k;
}
public String toString() {
return Integer.toString(i) + "-" + Integer.toString(j) + "-" + Integer.toString(k);
}
}
class Model {
public static final int Y = 7;
public static final int K = 42;
public static final int G = 3;
}
Catching the exception:
try {
Sleg illegal = new Sleg(1, 1, 90);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // This prints something like: Invalid sleg parameters: 1
}

I didn't understand your problem completely, but as per my understanding to implements Slegs = {<1,2,500> , <2,5,400>, <5,7,850>, <2,3,450>} and etc. like List Slegs = new ArrayList(); create separate class like below:
class slegs{
int i, j, k;
slegs(int i, int j, int k){
this.i = i;
this.j = j;
this.k = k;
}
}
You can also add your logic in the class like for assert / define or while creating an instance you can add checks.
Then you can create instance of these class and add them to list (slegs) using slegs.add(s1). To insert it in map just use the instance map.put(key, s1).

First, to use Sleg as a key of the HasMap or HasSet you have to corerctly define hashCode() and equals(). E.g. like this one:
class Sleg {
private final UUID id;
private final int i;
private final int j;
private final double l;
public Sleg(int i, int j, double l) {
id = UUID.randomUUID();
this.i = i;
this.j = j;
this.l = l;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Sleg))
return false;
Sleg sleg = (Sleg)obj;
return i == sleg.i && j == sleg.j && Double.compare(sleg.l, l) == 0;
}
#Override
public int hashCode() {
return Objects.hash(i, j, l);
}
}
Note: this class Sleg is ready to be a key of the HashMap.
Second, you want to assign an unique integer key with each Sleg instance. I could reccomend you to add this id directly into Skeg instance and increment it each time when you create new object:
class Sleg {
private final int id;
private static final AtomicInteger nextId = new AtomicInteger();
public Sleg(int i, int j, double l) {
id = nextId.incrementAndGet();
}
}

Related

Get value from HashMap by key

I need to compare the roman letters and get the correct integer out of it.
If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key.
The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now.
I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms.
package com.company;
import java.util.*;
public class Main {
static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>();
static {
romanNumbers.put("I", 1);
romanNumbers.put("V", 5);
romanNumbers.put("X", 10);
romanNumbers.put("L", 50);
romanNumbers.put("C", 100);
romanNumbers.put("D", 500);
romanNumbers.put("M", 1000);
}
public static void main(String[] args) {
romanToArabic("MMXX");
}
static int romanToArabic(String roman) {
ArrayList romanLetters = new ArrayList();
roman = roman.toUpperCase();
for (int i = 0; i < roman.length(); i++) {
char c = roman.charAt(i);
romanLetters.add(c);
}
// [M, M, X, X]
System.out.println(romanLetters);
// iterates over the romanLetters
for (int i = 0; i < romanLetters.size(); i++) {
System.out.println(romanLetters.get(i));
}
// retrive keys and values
for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) {
String key = (String) romanNumbersKey.getKey();
Object value = romanNumbersKey.getValue();
System.out.println(key + " " + value);
}
return 2020;
}
}
You could just Map.get each array element.
package com.company;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>();
static {
romanNumbers.put("I", 1);
romanNumbers.put("V", 5);
romanNumbers.put("X", 10);
romanNumbers.put("L", 50);
romanNumbers.put("C", 100);
romanNumbers.put("D", 500);
romanNumbers.put("M", 1000);
}
public static void main(String[] args) {
System.out.println(romanToArabic("MMXX"));
}
static int romanToArabic(String roman) {
ArrayList romanLetters = new ArrayList();
roman = roman.toUpperCase();
for (int i = 0; i < roman.length(); i++) {
char c = roman.charAt(i);
romanLetters.add(c);
}
// [M, M, X, X]
System.out.println(romanLetters);
// iterates over the romanLetters
int sum = 0;
for (int i = 0; i < romanLetters.size(); i++) {
String key = String.valueOf(romanLetters.get(i));
if (romanNumbers.containsKey(key)) {
sum += romanNumbers.get(key);
}
}
return sum;
}
}
As stated in the comments, this just answers your question of how to get values from an hashmap where keys are the array elements. It is not a solution to calculate the numeric value out of a roman number. For that, you will have to look at the next letter, and join if it is larger, before consulting the map for the final value to sum.
I'd like to suggest a completly different approach using an enum.
public enum RomanNumber {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int arabic;
RomanNumber(int arabic) {
this.arabic = arabic;
}
public int getArabicNumber() {
return arabic;
}
// This is obviously broken. IV wouldn't work for example.
public static int toArabic(String romanLetters) {
romanLetters = romanLetters.toUpperCase();
int arabicResult = 0;
for (int i = 0; i < romanLetters.length(); i++) {
char romanNumber = romanLetters.charAt(i);
// valueOf(String) returns the enum based on its name. So a String of "I" returns the RomanNumber I enum.
int arabicNumber = valueOf(String.valueOf(romanNumber)).getArabicNumber();
arabicResult = arabicResult + arabicNumber;
}
return arabicResult;
}
}
Can be used like this:
String romanNumber = "MMXX";
System.out.println(RomanNumber.toArabic(romanNumber));
Btw. every enum has an ordinal() method which returns the declaration position inside the enum. (I.ordinal() == 1 or V.ordinal() == 2) I think this could help you with the IV problem aswell. :)

Type casting in Java as a workaround to the absence of generic arrays

I have a class with a header defined as public class MaxPQ<Key extends Comparable<Key>>. Now, when I try making an array of Key, the way I do it in my constructor is as follows: Key[] pq = (Key[]) new Comparable[2];
This works fine but if I change Comparable to Object, I get an error. Why?
While in another code where the header looked like public class Stack<Item>, making an array of Item(s) like Item[] stack = (Item[]) new Object[1] worked just fine.
PS: I am following an online tutorial and this is what the code looks like:
public class MaxPQ<Key extends Comparable<Key>> {
private Key[] pq;
private int N;
public MaxPQ(int capacity) {
pq = (Key[]) new Comparable[capacity + 1];
}
public void insert(Key key) {
pq[++N] = key;
swim(N);
}
public Key delMax() {
Key key = pq[1];
exch(1, N--);
sink(1);
pq[N + 1] = null;
return key;
}
private void swim(int k) {
while(k > 1 && less(k/2, k)) {
exch(k, k/2);
k = k/2;
}
}
private void sink(int k) {
while (2*k < N) {
int j = 2*k;
if (j < N && less(j, j + 1)) j++;
if (less(j, k)) break;
exch(j, k);
k = j;
}
}
private boolean less(int p, int q) {
return pq[p].compareTo(pq[q]) < 0;
}
private void exch(int p, int q) {
Key temp = pq[p];
pq[p] = pq[q];
pq[q] = temp;
}
When a generic type has an upper bound, the erased type is that upper bound. That means that a class like
public class Stack<I> {
private I[] array;
}
is in fact compiled to something like
public class Stack {
private Object[] array;
}
whereas a class like
public class MaxPQ<Key extends Comparable<Key>> {
private Key[] array;
}
is compiled to something like
public class MaxPQ {
private Comparable[] array;
}
Thus, when executing
Key[] pq = (Key[]) new Comparable[2];
what is in fact executed is
Comparable[] pq = (Comparable[]) new Comparable[2];
which is fine. If you change it to Object[], you're in fact executing
Comparable[] pq = (Comparable[]) new Object[2];
which causes a ClassCastException, since an Object[] is not a Comparable[].
You should use a List<Key> instead of an array: you wouldn't have all these troubles.

Can't locate the problems in this simple Genetic Algorithm program

I have written a simple genetic algorithm program in java. What it is does is maximize the decimal value represented by the bits in the chromosome. Somehow mutation is not working as expected, e.g. causing two genes to mutate when just one is to change. The print statements I have included there show which to mutate, but in addition to that some more chromosomes get mutated. I can't figure out what the problem is :-(
Here are my java classes.
Gene.java
public class Gene {
private int value;
public Gene() {
value = Math.random() < 0.5 ? 0 : 1;
}
public Gene(int value) {
if (value != 0 && value != 1) {
throw new IllegalArgumentException("value must be either 0 or 1");
}
else {
this.value = value;
}
}
public void mutate() {
value = 1 - value;
}
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}
Chromosome.java
import java.util.ArrayList;
import java.util.List;
public class Chromosome implements Comparable {
private ArrayList<Gene> genes;
private final int chromosomeLength;
public Chromosome(int length) {
this.genes = new ArrayList<>();
this.chromosomeLength = length > 0 ? length : 16;
for (int i = 0; i < chromosomeLength; i++) {
this.genes.add(i, new Gene());
}
}
public List<Gene> getAllele(int fromIndex, int toIndex) {
return new ArrayList<>(genes.subList(fromIndex, toIndex));
}
public void setAllele(int fromIndex, List<Gene> allele) {
int lastIndex = fromIndex + allele.size();
if (lastIndex > chromosomeLength) {
throw new IndexOutOfBoundsException("the allele exceeds beyond the size of the chromosome");
}
for (int i = fromIndex, j = 0; i < lastIndex; i++, j++) {
genes.set(i, allele.get(j));
}
}
public int getChromosomeLength() {
return chromosomeLength;
}
public void setGeneAt(int index, Gene gene) {
genes.set(index, gene);
}
public Gene getGeneAt(int index) {
return genes.get(index);
}
public int value() {
return Integer.parseInt(this.toString(), 2);
}
#Override
public String toString() {
StringBuilder chromosome = new StringBuilder("");
genes.stream().forEach((Gene g) -> chromosome.append(g));
return chromosome.toString();
}
#Override
public int compareTo(Object anotherChromosome) {
Chromosome c = (Chromosome) anotherChromosome;
return this.value() - c.value();
}
}
GenePool.java
import java.util.ArrayList;
import java.util.Arrays;
public class GenePool {
private final ArrayList<Chromosome> genePool;
private final int genePoolSize;
private final int chromosomeLength;
private final double crossOverRate;
private final double mutationRate;
private int[] crossPoints;
public GenePool(int numOfChromosome, int chromosomeLength, double crossOverRate, double mutationRate) {
this.genePoolSize = numOfChromosome;
this.chromosomeLength = chromosomeLength > 0 ? chromosomeLength : 16;
this.crossOverRate = crossOverRate;
this.mutationRate = mutationRate;
crossPoints = new int[1];
crossPoints[0] = this.chromosomeLength / 2;
genePool = new ArrayList<>();
for (int i = 0; i < numOfChromosome; i++) {
genePool.add(new Chromosome(chromosomeLength));
}
}
public int getGenePoolSize() {
return genePoolSize;
}
public Chromosome getChromosomeAt(int index) {
return genePool.get(index);
}
public void setChromosomeAt(int index, Chromosome c) {
genePool.set(index, c);
}
public int getChromosomeLength() {
return chromosomeLength;
}
public Chromosome[] crossOver(Chromosome c1, Chromosome c2) {
Chromosome[] offsprings = new Chromosome[2];
offsprings[0] = new Chromosome(c1.getChromosomeLength());
offsprings[1] = new Chromosome(c1.getChromosomeLength());
Chromosome[] parentChromosomes = {c1, c2};
int selector = 0;
for (int i = 0, start = 0; i <= crossPoints.length; i++) {
int crossPoint = i == crossPoints.length ? c1.getChromosomeLength() : crossPoints[i];
offsprings[0].setAllele(start, parentChromosomes[selector].getAllele(start, crossPoint));
offsprings[1].setAllele(start, parentChromosomes[1 - selector].getAllele(start, crossPoint));
selector = 1 - selector;
start = crossPoint;
}
return offsprings;
}
public void mutateGenePool() {
int totalGeneCount = genePoolSize * chromosomeLength;
System.out.println("Mutating genes:");
for (int i = 0; i < totalGeneCount; i++) {
double prob = Math.random();
if (prob < mutationRate) {
System.out.printf("Chromosome#: %d\tGene#: %d\n", i / chromosomeLength, i % chromosomeLength);
genePool.get(i / chromosomeLength).getGeneAt(i % chromosomeLength).mutate();
}
}
System.out.println("");
}
public int getLeastFitIndex() {
int index = 0;
int min = genePool.get(index).value();
int currentValue;
for (int i = 1; i < genePoolSize; i++) {
currentValue = genePool.get(i).value();
if (currentValue < min) {
index = i;
min = currentValue;
}
}
return index;
}
public void saveFittest(ArrayList<Chromosome> offsprings) {
// sort in ascending order
offsprings.sort(null);
offsprings.stream().forEach((offspring) -> {
int leastFitIndex = getLeastFitIndex();
if (offspring.value() > genePool.get(leastFitIndex).value()) {
genePool.set(leastFitIndex, offspring);
}
});
}
public void evolve(int noOfGeneration) {
for (int generation = 1; generation <= noOfGeneration; generation++) {
System.out.println("Generation :" + generation);
ArrayList<Integer> selection = new ArrayList<>();
for (int i = 0; i < genePoolSize; i++) {
if (Math.random() <= crossOverRate) {
selection.add(i);
}
}
if (selection.size() % 2 == 1) {
selection.remove(selection.size() - 1);
}
ArrayList<Chromosome> offsprings = new ArrayList<>();
for (int i = 0; i < selection.size(); i += 2) {
int index1 = selection.get(i);
int index2 = selection.get(i + 1);
offsprings.addAll(Arrays.asList(crossOver(genePool.get(index1), genePool.get(index2))));
}
System.out.println("Before saving the offsprings");
displayChromosomes(genePool, "GenePool");
displayChromosomes(offsprings, "Offsprings");
saveFittest(offsprings);
System.out.println("Before mutation:");
displayChromosomes(genePool, "GenePool");
mutateGenePool();
System.out.println("After mutation:");
displayChromosomes(genePool, "GenePool");
System.out.println("\n\n");
}
}
public void displayChromosomes(ArrayList<Chromosome> geneList, String name) {
System.out.println(name);
if (geneList.isEmpty()) {
System.out.println("Empty list");
}
geneList.stream().forEach((c) -> {
System.out.println(c + " -> " + c.value());
});
System.out.println("");
}
}
GADemo.java
public class GADemo {
public static void main(String[] args) {
GenePool gp = new GenePool(6, 8, 0.25, 0.01);
gp.evolve(10);
}
}
After evolving for a number of generations, the chromosomes all tend to become exactly the same, or very similar. And the problem is that that value is not the maximum for that many bits, and sometimes even a small value. For example, for 8 bits the values should (tend to) approach 255, but this doesn't do so in my code. Someone please provide a hint where/how to look for and solve the problem.
Focus on these lines and imagine the references. These are from setAllele()
for (int i = fromIndex, j = 0; i < lastIndex; i++, j++) {
genes.set(i, allele.get(j));
}
You are basically copying the reference from one onto the other. They are the same Gene so whatever mutation you do on those genes, will also affect even other Chromosomes.
You must produce a deep copy here.
Initially each chromosome has an own list of genes. But when you do the crossover operation you set gene objects from one chromosome into the gene list of other chromosome.
When you evolve the system, the number of shared genes will rise and therefore ultimately all chromosomes will share the same genes. No matter how you mutate a gene the chromosomes are not affected.
EDIT:
As Incognito also answered the setAllele method seems to be the culprit where gene sharing starts. You may want to introduce a method in the gene class where you can set its value given another gene.

I am getting null values in my Array

I am playing around with an ArrayList and trying to get it to grow twice it's size every time it exceeds it's size. Here is my add method:
public class ArrayExpander
{
private int size;
private int noOfItems;
private Object[] store;
private final int INITIALSIZE = 2;
public ArrayExpander()
{
store = new Object[INITIALSIZE];
noOfItems = 0;
size = INITIALSIZE;
}
public void add(Object obj)
{
growBufferIfNecessary();
store[size++] = obj;
/*for (int i = size - 1; i < store.length; i++)
{
store[i] = store[i - 1];
store[i] = obj;
}*/
}
public String toString()
{
String temp = "[" + store[0];
for (int i = 1; i < size; i++)
{
temp = temp + "," + store[i];
}
temp = temp + "]";
return temp;
}
private void growBufferIfNecessary()
{
if (size == store.length)
{
Object[] newStore = new Object[2 * store.length];
for (int i = 0; i < store.length; i++)
{
newStore[i] = store[i];
}
store = newStore;
}
}
public static void main(String[] args)
{
ArrayExpander ae = new ArrayExpander();
//System.out.println(ae);
ae.add("a");
ae.add("b");
System.out.println(ae);
ae.add("c");
ae.add("d");
ae.add("e");
ae.add("f");
ae.add("g");
ae.add("h");
System.out.println(ae);
ae.add("i");
System.out.println(ae);
}
}
Here is my output:
[null,null]
[null,null,a,b]
[null,null,a,b,c,d,e,f,g,h]
[null,null,a,b,c,d,e,f,g,h,i]
I can't figure out why I am getting the null statements. The first line should be a,b and then the arraylist should double in size and be a,b,c,d. I have it set for final int INITIALSIZE = 2.
The output I am looking for is
[a,b]
[a,b,c,d]
[a,b,c,d,e,f,g,h]
[a,b,c,d,e,f,g,h,i,null,null,null,null,null,null,null]
This code will work for you. size should be referring to the size of your array while noOfItems refers to the number of items in your array. You were kind of mixing the 2 up. I only changed a couple things in your add() and growBufferIfNecessary().
public class ArrayExpander
{
private int size;
private int noOfItems;
private Object[] store;
private final int INITIALSIZE = 2;
public ArrayExpander()
{
store = new Object[INITIALSIZE];
noOfItems = 0;
size = INITIALSIZE;
}
public void add(Object obj)
{
growBufferIfNecessary();
store[noOfItems++] = obj;
}
public String toString()
{
String temp = "[" + store[0];
for (int i = 1; i < size; i++)
{
temp = temp + "," + store[i];
}
temp = temp + "]";
return temp;
}
private void growBufferIfNecessary()
{
if (noOfItems == size)
{
size = 2 * size;
Object[] newStore = new Object[size];
for (int i = 0; i < store.length; i++)
{
newStore[i] = store[i];
}
store = newStore;
}
}
public static void main(String[] args)
{
ArrayExpander ae = new ArrayExpander();
//System.out.println(ae);
ae.add("a");
ae.add("b");
System.out.println(ae);
ae.add("c");
ae.add("d");
ae.add("e");
ae.add("f");
ae.add("g");
ae.add("h");
System.out.println(ae);
ae.add("i");
System.out.println(ae);
}
}
Try this. If you notice I replaced size in a couple spots with noOfItems. You were really close you just needed to change a couple things.
Manually copying arrays with loops is such a pain, use System.arraycopy(Object,int,Object,int,int) like
private int size = 0;
private Object[] store = new Object[INITIALSIZE];
private void growBufferIfNecessary() {
if (size >= store.length) {
Object[] newStore = new Object[2 * store.length];
System.arraycopy(store, 0, newStore, 0, store.length);
store = newStore;
}
}
I eliminated noOfItems. You don't need it, your add method is just
public void add(Object obj) {
growBufferIfNecessary();
store[size++] = obj;
}
Finally, your toString() could use Arrays.copyOf(T[], int) like
#Override
public String toString() {
return Arrays.toString(Arrays.copyOf(store, size));
}
And then I got your expected output
[a, b]
[a, b, c, d, e, f, g, h]
[a, b, c, d, e, f, g, h, i]

Null Pointer Exception in LinkedList Hash Table

So I'm creating a hash table with LinkedLists using the multiplication method. As an instance variable I define the LinkedList "T" that I'll be using, and in the constructor of the class I specify the size of T. However, every time I run my Driver testing class, I get NullPointerExceptions on everything I try to reference anything in T[]. Am I overlooking something? I've spent over an hour trying to figure it out.
ChainedHashTable class:
public class ChainedHashTable
{
private LinkedList<Integer>[] T;
private int m;
private double A;
public ChainedHashTable(int n)
{
for (m = 1; m < n; m *= 2);
T = new LinkedList[m];
Random random = new Random();
int s = random.nextInt(Integer.MAX_VALUE);
A = (s * 1.00) / Integer.MAX_VALUE;
}
public void insert(Integer key)
{
T[hash(key)].add(Integer.valueOf(key));
}
public void delete(int key)
{
T[hash(key)].remove(Integer.valueOf(key));
}
public Integer search(int key)
{
int n = T[hash(key)].indexOf(key);
if (n == -1)
return -1;
else
return T[hash(key)].get(n);
}
private int hash(int key)
{
System.out.println((int)(m * ((key * A) % 1)));
return (int)(m * ((key * A) % 1));
}
public void printTable()
{
for (int i = 0; i < T.length; i++)
{
System.out.println("index: " + i + " " + T[i]);
}
}
}
Driver class:
public class Driver
{
public static void main(String[] args)
{
ChainedHashTable test1 = new ChainedHashTable(20);
test1.printTable();
test1.insert(4);
test1.insert(54);
test1.insert(6);
test1.insert(3);
test1.insert(26);
test1.insert(54);
test1.insert(11);
test1.insert(10);
test1.insert(76);
test1.insert(42);
test1.insert(41);
test1.insert(32);
test1.insert(87);
test1.insert(76);
test1.insert(72);
test1.insert(57);
test1.insert(29);
test1.insert(16);
test1.insert(92);
test1.insert(64);
test1.printTable();
}
}
You are creating an array of references to type LinkedList and setting them to their initial state, which is null.
T = new LinkedList[m];
T now is an array of the computed size m. You need to initialize the objects inside of the array.
T = new LinkedList[m];
for (int i = 0; i < m; i++) {
T[i] = new LinkedList<>();
}

Categories

Resources