I am not sure if I expressed myself correctly with the title but I will try to be more specific here.
What I have:
An arraylist with clients/customers.
An arraylist with phone numbers assigned to the clients/customers.
My Client class:
import java.util.*;
public class Clients implements Comparable<Clients> {
private String name;
private String address;
public ArrayList<Share> shareList = new ArrayList<Share>();
private PhoneBook phoneBook = new PhoneBook();
public Clients(String name, String address) {
this.name = name;
this.address = address;
}
public void addPhoneDescription(String description) {
phoneBook.addPhoneDescription(description);
}
public void addPhoneNumber(String number) {
phoneBook.addPhoneNumber(number);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public PhoneBook getPhoneBook() {
return phoneBook;
}
public boolean equals(Object obj) {
Clients c = (Clients) obj;
return this.name.equals(c.name);
}
public String toString() {
String result;
result = ("\n" + "Name: " + this.getName() + "\n" + "Address: "
+ this.getAddress() + "\n" + "Phone description: " + this
.getPhoneBook());
return result;
}
public int compareTo(Clients other) {
return name.compareTo(other.name);
}
}
This is my PhoneBook class consisting of set/get methods:
import java.util.ArrayList;
public class PhoneBook {
private ArrayList<String> numbersList = new ArrayList<String>();
private ArrayList<String> phoneDescription = new ArrayList<String>();
public void addPhoneDescription(String description) {
phoneDescription.add(description);
}
public void addPhoneNumber(String number) { // Add the phone number to the numbersList
numbersList.add(number);
}
public String toString(){
return numbersList.toString() + phoneDescription.toString();
}
}
What I want to achieve: So if I create lets say 3 clients and 2 of them have the same numbers I want to print out those 2 clients with the number they share/have in common and so on. I have create a method over at my Program class:
public void findDuplicatedNumbers() {
// method that looks for duplicated numbers that clients have
ArrayList<Integer> sNumber = new ArrayList<>();
ArrayList<Integer> duplicateNumber = new ArrayList<>();
for (int i = 0; i < clientList.size(); i++) {
for (int k = 0; k < (clientList.get(i).getPhoneBook().size); k++) {
if (sNumber.contains(clientList.get(i).getPhoneBook().get(k).getNumber())) {
if (duplicateNumber.contains(clientList.get(i).getPhoneBook().get(k).getNumber())) {
} else {
// adds to duplicateNumber arrayList
duplicateNumber.add(clientList.get(i).getPhoneBook().get(k).getNumber());
}
} else {
// adds to sNumber arrayList
sNumber.add(clientList.get(i).getPhoneBook().get(k).getNumber());
}
}
}
for (int i = 0; i < duplicateNumber.size(); i++) {
System.out.println("Phone number: " + duplicateNumber.get(i) + " is share with these clients: ");
for (int k = 0; k < clientList.size(); k++) {
for (int p = 0; p < (clientList.get(p).getPhoneBook().size()); p++) {
if (duplicateNumber.get(i) == clientList.get(k).getPhoneBook().get(p).getNumber()) {
System.out.println(clientList.get(k).getName() + ", ");
}
}
}
System.out.println("\n");
}
}
Puh .. quiet a lot of code for a simple task. KISS (keep it simple):
public void findDuplicatedNumbers() {
Map<String, Set<Client> > duplicates =
new HashMap<String, Set<Client> >();
Set<String> phoneNumbers = new HashSet<String>();
for(Client client : clientList) {
PhoneBook phoneBook = client.getPhoneBook();
phoneNumbers.addAll(phoneBook.getNumberList());
}
for(String phoneNumber : phoneNumbers) {
Set<Client> clients = findClientsByPhoneNumber(phoneNumber);
if(clients.size() > 1)
duplicates.put(phoneNumber, clients);
}
for(Entry<String, Set<Client> entry : duplicates.entrySet()) {
System.out.println("phonenumber " + entry.getKey() + " is dubplicated / is share with these clients:");
for(Client client : entry.getValue()) {
System.out.println(client.getName());
}
}
}
protected Set<Client> findClientsByPhoneNumber(String phoneNumber) {
Set<Client> clients = new HashSet<Client>();
for(Client client : clientList ) {
List<String> phoneNumbers = client.getPhonebook().getNumberList();
if(phoneNumbers.contains(phoneNumber)) {
clients.add(client);
}
}
return clients;
}
This is not only cleaner structured and implements an additional interface for finding clients by number but also more performance in most cases.
Just be clean about what you want to do: If you want to store a list of unique objects, it is one of the Set - implementations. If you want to store something by a key, use a Map - implementation.
public class PhoneBook {
private ArrayList<String> numbersList = new ArrayList<String>();
private ArrayList<String> phoneDescription = new ArrayList<String>();
public void addPhoneDescription(String description) {
phoneDescription.add(description);
}
public void addPhoneNumber(String number) { // Add the phone number to the numbersList
numbersList.add(number);
}
public String toString(){
return numbersList.toString() + phoneDescription.toString();
}
public ArrayList<String> findDuplicatedNumbers() {
ArrayList<String> dupes = new ArrayList<String>();
Collections.sort(numbersList);
Iterator<String> iter = numbersList.iterator();
while(iter.hasNext()) {
String next = iter.next();
if(iter.hasNext() && next == iter.next()) {
dupes.add(next);
}
}
return dupes;
}
}
Related
import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}
I've implemented the interface comparable and the method compareTo(). I have a list named randomHumans that contains 10 objects. 5 objects with three fields: name, age and year they started studying, and 5 objects with two fields: name and age. I would like to sort my list, and tried using:
Collections.sort(randomHumans);
This gave me the following error message:
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Object>)
I then tried this code:
Collections.sort((List<T>) randomObjects);
But it just gives me two new error messages. Maybe I need to specify what field it should sort after, but I can't find how to implement this. Any help would be greatly appreciated.
main method:
public static void main (String[] args) {
ArrayList<Object> randomObjects = new ArrayList<Object>();
for (int j=0; j<5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects.toString());
//Collections.sort(randomObjects);
}
Human class:
class Human implements Comparable<Human> {
int age;
String name;
public Human (int myAge, String myName) {
name = myName;
age = myAge;
}
public Human() {
this(randomAge(),randomName());
}
public int compareTo(Human o) {
return this.age - o.age;
}
protected static int randomAge() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(100);
}
protected static String randomName() {
Random randomGenerator = new Random();
return "Name"+randomGenerator.nextInt(15);
}
public int getAge(){
return age;
}
public String getName() {
return name;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old\n";
}
}
Fysiker class:
public class Fysiker extends Human {
int year;
public Fysiker(int myAge2, String myName2, int myYear) {
name = myName2;
year = myYear+1932;
if (myAge2 >= 15+(2017-myYear)) {
age = myAge2;
} else {
age = 15+(2017-year);
}
}
public Fysiker() {
this(randomAge(),randomName(), randomYear());
}
protected static int randomYear() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(83);
}
public int getYear(){
return year;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old" + "\nStarted Physics: " + year+"\n";
}
}
Just change the generic parameter from Object to Human
public static void main (String[] args) {
List<Human> randomObjects = new ArrayList<>();
for (int j = 0; j < 5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects);
Collections.sort(randomObjects);
}
When you write Collections.sort(randomHumans); randomHumans must be a List of Comparable. If you are 'forced' to use a List of Object, you must give a Comparator to explain how to compare each object :
Collections.sort(randomHumans, humanComparator);
It's all explained in the offcial documentation :
sort(java.util.List)
sort(java.util.List, java.util.Comparator)
I've been working on this AP Problem all day with no luck. If anyone can help, it would be appreciated.
I have an ArrayList of Strings composed of names and addresses. After the addresses, there is an empty String and the next name starts. The method getAddress takes a String parameter (a name) and returns the address of the pereson (the lines after the name including the empty String, but stopping there). I'm having trouble writing this method.
import java.util.ArrayList;
public class Recipients {
ArrayList<String> lines = new ArrayList<String>();
public String extractCity(String cityZip) {
int pos = cityZip.indexOf(",");
return cityZip.substring(0, pos);
}
public void printNames() {
System.out.println(lines.get(0));
for (int i = 0; i < lines.size()-1; i++)
if (lines.get(i).substring(0, lines.get(i).length()).equals(""))
System.out.println(lines.get(i+1));
}
public String getAddress(String name) {
String address = "";
int ct = 0;
int place = 0;
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).substring(0, lines.get(i).length()).equals(name)) {
place = i;
for (int j = i+1; j < lines.size(); j++) {
ct = j;
if (!lines.get(i).substring(0, lines.get(i).length()).equals("")) {
ct++;
}
}
for (int k = place; k < ct; k++) {
address = address + lines.get(i);
}
}
}
return address;
}
public void main() {
lines.add("Mr. J Adams");
lines.add("Rose St.");
lines.add("Ithaca, NY 14850");
lines.add("");
lines.add("Jack S. Smith");
lines.add("12 Posy Way");
lines.add("Suite #201");
lines.add("Glendale, CA 91203");
lines.add("");
lines.add("Ms. M.K. Delgado");
lines.add("2 River Dr.");
lines.add("");
System.out.println(getAddress("Jack S. Smith"));
System.out.println("test line break");
}
}
Thank you for your time.
EDIT: This method is supposed to be written in the Recipients class. It has an assumed constructor and I've written other methods inside the class. I've edited the class. I'm having trouble with the logic.
Worksheet says: Write the getAddress method of the Recipients class. This method should return a string that contains only the address of the corresponding name parameter. For example, if name is "Jack S. Smith", a string containing the three subsequent lines of his address should be returned. This string should contain line breaks in appropriate places, including after the last line of the address.
public String getAddress(String name)
You should create class for saving name and address. Please find below mentioned approach.
package hello;
import java.util.ArrayList;
import java.util.List;
class Employee {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class So3 {
public static void main(String[] args) {
List<String> lines = new ArrayList<String>();
lines.add("Mr. J Adams");
lines.add("Rose St.");
lines.add("Ithaca, NY 14850");
lines.add("");
lines.add("Jack S. Smith");
lines.add("12 Posy Way");
lines.add("Suite #201");
lines.add("Glendale, CA 91203");
lines.add("");
lines.add("Ms. M.K. Delgado");
lines.add("2 River Dr.");
lines.add("");
List<Employee> employees = new ArrayList<Employee>();
Employee employee = new Employee();
for (String str : lines) {
if (str.isEmpty()) {
if (employee.getName() != null && employee.getAddress() != null) {
employees.add(employee);
employee = new Employee();
}
} else if (employee.getName() == null) {
employee.setName(str);
} else {
if (employee.getAddress() == null) {
employee.setAddress(str);
} else {
employee.setAddress(employee.getAddress() + " " + str);
}
}
}
if (employee.getName() != null && employee.getAddress() != null) {
employees.add(employee);
}
System.out.println(getAddress(employees, "Ms. M.K. Delgado"));
}
private static String getAddress(List<Employee> employees, String name) {
if (employees != null && name != null) {
for (Employee employee : employees) {
if (name.equals(employee.getName())) {
return employee.getAddress();
}
}
}
return null;
}
}
If you have to use as you have wanted then you need to modify your getAddress method. Try the following getAddress method in your code:
public String getAddress(String name) {
String address = "";
boolean nameFound=false;
for(String str:lines)
{
if(!nameFound && str.equals(name))
nameFound=true;
else if(nameFound && str.isEmpty())
break;
else if(nameFound && !str.isEmpty())
address+=str;
}
return address;
}
You should use HashMap rather than an ArrayList for this. This is a perfect scenario to use HashMap instead.
public class APProblem {
Map<String, List<String>> lines2 = new HashMap<>();
public List<String> getAddress(String name) {
return lines2.get(name);
}
public void main() {
String name = "Mr. J Adams";
List<String> address = Arrays.asList("Rose St.", "Ithaca, NY 14850");
lines2.put(name, address);
name = "Jack S. Smith";
address = Arrays.asList("12 Posy Way", "Suite #201", "Glendale, CA 91203");
lines2.put(name, address);
System.out.println(getAddress("Jack S. Smith"));
System.out.println("Testing line break.");
}
}
I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
I want to accept input from user to populate an Array list of Person. for some reason. I can't get it to work. I can add an item into the list I have created below are my code for reference. in the SimplepersonDatabase class in switch function case 2:, I want to accept an an input of names, date of birth from the user and the program should automatically assign the position number starting from
e.g
001. Damien Kluk September, 12.09.1975
002. James Hunt January , 12.09.2000
I should be able to also delete a person and sort the list of Persons. here are what I have implemented so far.
public class Person { //Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
class List {//List.java
int MAX_LIST = 20;
Person[] persons;
int count;
public List() {
persons = new Person[MAX_LIST];
count=0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
}
public class SimplePersonDataBase { //SimplePersonDataBase.java
private static List list;
private static int nextPersonId;
public static void main(String[] args) {
go();
}
public static void go() {
List link = new List();
TextIO.put("Welcome to the SimplePersonDatabase.\n");
TextIO.putln();
int option;
do{
TextIO.put("available options:\n1) list\n2) add\n3) remove\n4) sort\n5) find\n6) settings\n0) quit\nyour choice:");
option = TextIO.getInt();
switch(option){
case 1:
PersonFunctions.display();
break;
case 2: // Should accept inputs from a user and update the Persons database
TextIO.put("Firstname:");
String fn = TextIO.getlnWord();
TextIO.put("Lastname:");
String ln = TextIO.getlnWord();
Date date = DateFunctions.scanDate();
int pos = link.count;
Person item = new Person(fn,ln,date,pos);
add(item);
break;
case 3:
break;
case 4:
TextIO.putln("sort by:\n1) Firstname\n2) Birth\nall other values: lastname");
switch(TextIO.getInt()){
case 1:
break;
case 2:
break;
default :
break;
}
break;
case 5:
break;
case 6:
break;
case 0:
TextIO.put("Thank you for using the SimplePersonDatabase.");
break;
case 99:
break;
default :
TextIO.put("illegal option.");
break;
}
}while(option !=0);
}
public static boolean add(Person personadd) {
personadd.id = nextPersonId;
++nextPersonId;
list.add(personadd);
return true;
}
}
Your list is working well (I tried + or -)
import java.util.Arrays;
import java.util.Date;
class Person { // Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
the list
public class MyList {
int MAX_LIST = 20;
Person[] persons;
int count;
public MyList() {
persons = new Person[MAX_LIST];
count = 0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
System.out.println("enlarging");
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
public Person get(int i) {
return persons[i];
}
public static void main(String[] args) {
MyList list = new MyList();
for (int i=0; i<1000; i++) {
list.add(new Person("fn"+i,"sn"+i,new Date(),i));
System.out.println(list.get(i) + " " + list.count);
}
}
}
the problem is in the "go" function, why you are using link and then you add in list?