How to determine which input value was entered the most - java

I am having a hard time figuring how to determine which productType was inputted the most. For example, a person could input "water", "water", "coffee", and "milk". My expected output would be "Water was the most ordered product." This is my mainline logic. Can anyone help?
public static void main(String[] args) {
final int MAX_GUESTS = 16;
final int MAX_DRINKS = 48;
double[] drinkCosts = new double[MAX_DRINKS];
int count = 0;
String productType = getProductType();
while (!productType.equals("-1")) {
if (count < MAX_GUESTS) {
count++;
String productVariation = getProductVariation(productType);
for (int i = 0; i < count; i++) {
drinkCosts[count] = getDrinkCost(productVariation);
}
}
else {
JOptionPane.showMessageDialog(null, "Come back tomorrow.");
}
productType = getProductType();
}
double total = getTotal(drinkCosts);
print(total);
}

I would recommend using a java.util.HashMap<>. Use a String for the key type (the productType) and use Integer for the value type (the number of occurrences of that productType).
Each time you read in a productType (at the start of your while loop), check if the productType is already a key in the map. If so, increment the count that it maps to by one. If not, use the HashMap.put(String key, Integer value) method to add the productType to the map with a count of 1.
After your while loop, simply loop through the map to check which productType was entered the most (has the highest count):
int highestCount = -1;
String mostEnteredProductType = null;
for (Entry<String,Integer> entry : map.entrySet()) {
if (entry.getValue() > highestCount) {
highestCount = entry.getValue();
mostEnteredProductType = entry.getKey();
}
}
System.out.println(mostEnteredProductType + " was the most ordered product.");
EDIT:
To do this with only arrays, you will need to have two arrays, one for the productType and one for the number of occurrences of that productType. Since arrays have a fixed length, you will need to initialize them to the number of possible productTypes (I think that is what MAX_DRINKS is?).
So, we create two arrays:
String[] productTypes = new String[MAX_DRINKS];
int[] counts = new int[MAX_DRINKS];
These arrays will essentially function as a map, with each productType in the String array mapping to the count at the same index in counts (e.g., productTypes[5] was entered counts[5] times).
Then, when you read in a productType in the while loop, loop through productTypes. If you find that type, increment the corresponding index of counts (e.g., if the productType is at productTypes[5], increment counts[5]. If not (if you reach an element that is null in productTypes before finding the type that was entered), set that element to the given productType, and set the corresponding index of counts to 1.
Then, simply change the above code fragment I gave to this:
int highestCount = 0;
String mostEnteredProductType = null;
for (int i = 0; i < NUM_DRINKS; i++) {
// Once we reach a null productType, we have reached the end of the
// entered productTypes
if (productTypes[i] == null) {
break;
} else if (counts[i] > highestCount) {
highestCount = counts[i];
mostEnteredProductType = productTypes[i];
}
}
// Should probably check that mostEnteredProductType isn't null here.
System.out.println(mostEnteredProductType + " was the most ordered product.");

Related

i want to count occurrence of each word in a given sentence in java

beginner at java was asked in an interview
here i have to count the occurrence of each word in a given sentence.
for eg( "chair is equal to chair but not equal to table."
Output : chair :2,
is :1,
equal :2,
to :2,
but :1,
not :1,
table :1 )
I have written some part of the code and tried using for loop but i failed....
public static void main(String[] args)
{
int counter = 0;
String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";
String[] b =a.split(" "); //stored in array and splitted
for(int i=0;i<b.length;i++)
{
counter=0;
for(int j<b.length;j>0;j--)
{
if(b[i] = b[j])
//
}
}
}
}
Use a hashmap to count frequency of objects
import java.util.HashMap;
import java.util.Map.Entry;
public class Funly {
public static void main(String[] args) {
int counter = 0;
String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";
String[] b = a.split(" "); // stored in array and splitted
HashMap<String, Integer> freqMap = new HashMap<String, Integer>();
for (int i = 0; i < b.length; i++) {
String key = b[i];
int freq = freqMap.getOrDefault(key, 0);
freqMap.put(key, ++freq);
}
for (Entry<String, Integer> result : freqMap.entrySet()) {
System.out.println(result.getKey() + " " + result.getValue());
}
}
}
Quite easy since Java8:
public static Map<String, Long> countOccurrences(String sentence) {
return Arrays.stream(sentence.split(" "))
.collect(Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
}
I would also remove non literal symbols, and convert to lowecase before running:
String tmp = sentence.replaceAll("[^A-Za-z\\s]", "");
So your final main method for interview will be:
ppublic static void main(String[] args) {
String sentence = "To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";
String tmp = sentence.replaceAll("[^A-Za-z\\s]", "").toLowerCase();
System.out.println(
countOccurrences(tmp)
);
}
Output is:
{diligent=1, a=1, work=1, myself=1, opportunity=1, challenging=1, an=2, associate=1, innovative=1, that=1, with=1, provide=1, and=2, provides=1, organization=1, to=2, job=1}
A simple (but not very efficient) way would be to add all the elements to a set, which doesn't allow duplicates. See How to efficiently remove duplicates from an array without using Set. Then iterate through the set and count the number of occurrences in your array, printing out the answer after each set element you check.
There are several solutions to this and I'm not going to provide you with any of them. However, I'm going to give you a rough outline of one possible solution:
You could use a Map, for example a HashMap, where you use the words as keys and the number of their occurrence as values. Then, all you need to do is to split the input string on spaces and iterate over the resulting array. For each word, you check if it already exists in the map. If so you increase the value by one, otherwise you add the word to the map and set the value to 1. After that, you can iterate over the map to create the desired output.
You need to use Map data structure which stores data in key-value pairs.
You can use the HashMap (implementation of Map) to store each word as key and their occurance as the value inside the Map as shown in the below code with inline comments:
String[] b =a.split(" "); //split the array
Map<String, Integer> map = new HashMap<>();//create a Map object
Integer counter=null;//initalize counter
for(int i=0;i<b.length;i++) { //loop the whole array
counter=map.get(b[i]);//get element from map
if(map.get(b[i]) == null) { //check if it already exists
map.put(b[i], 1);//not exist, add with counter as 1
} else {
counter++;//if already eists, increment the counter & put to Map
map.put(b[i], counter);
}
}
Using simple For loops
public static void main(String[] args) {
String input = "Table is this Table";
String[] arr1 = input.split(" ");
int count = 0;
for (int i = 0; i < arr1.length; i++) {
count = 0;
for (int j = 0; j < arr1.length; j++) {
String temp = arr1[j];
String temp1 = arr1[i];
if (j < i && temp.contentEquals(temp1)) {
break;
}
if (temp.contentEquals(temp1)) {
count = count + 1;
}
if (j == arr1.length - 1) {
System.out.println(">>" + arr1[i] + "<< is present >>" + count + "<< number of times");
}
}
}
}

How can I find the most frequent word in a huge amount of words (eg. 900000)

I am facing a task which is generating 900000 random words and then print out the most frequent one. So here is my algorithm:
1. move all number into a collection rather than printhing out them
2. for (900000...){move the frequency of Collection[i] to another collection B}
** 90W*90W is too much for a computer(lack of efficiency)
3. find the biggest number in that collection and the index.
4. then B[index] is output.
But the thing is that my computer cannot handle the second step. So I searched on this website and find some answer about find the frequency of word in a bunch of words and I viewed the answer code, but I haven't find a way to apply them into huge amount of words.
Now I show my code here:
/** Funny Words Generator
* Tony
*/
import java.util.*;
public class WordsGenerator {
//data field (can be accessed in whole class):
private static int xC; // define a xCurrent so we can access it all over the class
private static int n;
private static String[] consonants = {"b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","z"};
private static String[] vowels = {"a", "e", "i", "o", "u"};
private static String funnyWords = "";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = 900000; // words number
xC = sc.nextInt(); // seeds (only input)
/* Funny word list */
ArrayList<String> wordsList = new ArrayList<String>();
ArrayList<Integer> frequencies = new ArrayList<Integer>();
int maxFreq;
for (int i = 0; i < times; i++) {
n = 6; // each words are 6 characters long
funnyWords = ""; // reset the funnyWords each new time
for (int d = 0; d < n; d ++) {
int letterNum = randomGenerator(); /* random generator will generate numbers based on current x */
int letterIndex = 0; /* letterNum % 19 or % 5 based on condition */
if ((d + 1) % 2 == 0) {
letterIndex = letterNum % 5;
funnyWords += vowels[letterIndex];
}
else if ((d + 1) % 2 != 0) {
letterIndex = letterNum % 19;
funnyWords += consonants[letterIndex];
}
}
wordsList.add(funnyWords);
}
/* put all frequencies of each words into an array called frequencies */
for (int i = 0; i < 900000; i++) {
frequencies.add(Collections.frequency(wordsList, wordsList.get(i)));
}
maxFreq = Collections.max(frequencies);
int index = frequencies.indexOf(maxFreq); // get the index of the most frequent word
System.out.print(wordsList.get(index));
sc.close();
}
/** randomGenerator
* param: N(generate times), seeds
* return: update the xC and return it */
private static int randomGenerator() {
int a = 445;
int c = 700001;
int m = 2097152;
xC = (a * xC + c) % m; // update
return xC; // return
}
}
So I have realized that maybe there is a way skip the second step somehow. Anyone can give me a hint? Just a hint not code so I can try it myself will be great! Thx!
Modified:
I see lots of your answer code contains "words.stream()", I googled it and I couldn't find it. Could you guys please tell me where I can find this kind of knowledge? this stream method is in which class? Thank you!
You can do it using Java Lambdas (requires JDK 8). Also notice that you can have words with equal frequency in your word list.
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("World");
words.add("Hello");
words.add("World");
words.add("Hello");
// Imagine we have 90000 words in word list
Set<Map.Entry<String, Integer>> set = words.stream()
// Here we create map of unique words and calculates their frequency
.collect(Collectors.toMap(word -> word, word -> 1, Integer::sum)).entrySet();
// Find the max frequency
int max = Collections
.max(set, (a, b) -> Integer.compare(a.getValue(), b.getValue())).getValue();
// We can have words with the same frequency like in my words list. Let's get them all
List<String> list = set.stream()
.filter(entry -> entry.getValue() == max)
.map(Map.Entry::getKey).collect(Collectors.toList());
System.out.println(list); // [Hello, World]
}
}
This can basically be broken down into two steps:
Compute the word frequencies, as a Map<String, Long>. There are several options for this, see this question for examples.
Computing the maximum entry of this map, where "maximum" refers to the entry with the highest value.
So if you're really up to it, you can write this very compactly:
private static <T> T maxCountElement(List<? extends T> list)
{
return Collections.max(list.stream().collect(Collectors.groupingBy(
Function.identity(), Collectors.counting())).entrySet(),
(e0, e1) -> Long.compare(e0.getValue(), e1.getValue())).getKey();
}
Edited in response to the comment:
The compact representation may not be the most readable. Breaking it down makes the code a bit elaborate, but may make clearer what is happening there:
private static <T> T maxCountElement(List<? extends T> list)
{
// A collector that receives the input elements, and converts them
// into a map. The key of the map is the input element. The value
// of the map is the number of occurrences of the element
Collector<T, ?, Map<T, Long>> collector =
Collectors.groupingBy(Function.identity(), Collectors.counting());
// Create the map and obtain its set of entries
Map<T, Long> map = list.stream().collect(collector);
Set<Entry<T, Long>> entrySet = map.entrySet();
// A comparator that compares two map entries based on their value
Comparator<Entry<T, Long>> comparator =
(e0, e1) -> Long.compare(e0.getValue(), e1.getValue());
// Compute the maximum element of the set of entries. That is,
// the entry with the largest value (which is the entry for the
// element with the maximum number of occurrences)
Entry<T, Long> entryWithMaxValue =
Collections.max(entrySet, comparator);
return entryWithMaxValue.getKey();
}
HashMap is one of the fastest data structures, just loop through each words, use it as key to the HashMap, inside the loop, make the counter the value of the hashMap.
HashMap<string, Integer> hashMapVariable = new HashMap<>();
...
//inside the loop of words
if (hashMapVariable.containsKey(word){
hashMapVariable.put(key, hashMapVariable.get(key) + 1);
} else {
hashMapVariable.put(word, 1);
}
...
for each key(word) just increment the value as associated with the key. although you have to check if the key exits ( in java its hashMapVariable.containsKey("key") ). if its exits then just increament else add it to the HashMap. by doing this you are not restoring the whole data you are only making every key just one and the number of times it occurs as value to the key.
At the end of the loop the most frequent word will have the highest counter/value.
you can use a HashMap and the key store word and the value is correspond times
pseudocode as below:
String demo(){
int maxFrequency = 0;
String maxFrequencyStr = "";
String strs[] ;
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i = 0; i < 900000;i++){//for
if(map.containsKey(strs[i])){
int times = map.get(strs[i]);
map.put(strs[i], times+1);
if(maxFrequency<times+1){
maxFrequency = times + 1;
maxFrequencyStr = strs[i];
}
}
else{
map.put(strs[i], 1);
if(maxFrequency<1){
maxFrequency = 1;
maxFrequencyStr = strs[i];
}
}
}//for
return maxFrequencyStr;
}

Applying Linear and Binary Searches to Arrays

I have to create a program that takes a user input (a number) and then the program should have that number and apply a search to the array and output the corresponding title by matching the index and the number the user inputted. However during run time, nothing happens. I have set breakers in my code and noticed a problem with the for loop (search algorithm). Please help me and let me know what is wrong is my search algorithm. What I am trying to do is use the number of that the user inputs to match a index and then output the book title that is stored in the index.
private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// declares an array
String[] listOfBooks = new String [101];
// assigns index in array to book title
listOfBooks[1] = "The Adventures of Tom Sawyer";
listOfBooks[2] = "Huckleberry Finn";
listOfBooks[4] = "The Sword in the Stone";
listOfBooks[6] = "Stuart Little";
listOfBooks[10] = "Treasure Island";
listOfBooks[12] = "Test";
listOfBooks[14] = "Alice's Adventures in Wonderland";
listOfBooks[20] = "Twenty Thousand Leagues Under the Sea";
listOfBooks[24] = "Peter Pan";
listOfBooks[26] = "Charlotte's Web";
listOfBooks[31] = "A Little Princess";
listOfBooks[32] = "Little Women";
listOfBooks[33] = "Black Beauty";
listOfBooks[35] = "The Merry Adventures of Robin Hood";
listOfBooks[40] = "Robinson Crusoe";
listOfBooks[46] = "Anne of Green Gables";
listOfBooks[50] = "Little House in the Big Woods";
listOfBooks[52] = "Swiss Family Robinson";
listOfBooks[54] = "The Lion, the Witch and the Wardrobe";
listOfBooks[54] = "Heidi";
listOfBooks[66] = "A Winkle in Time";
listOfBooks[100] = "Mary Poppins";
// gets user input
String numberInput = txtNumberInput.getText();
int number = Integer.parseInt(numberInput);
// Linear search to match index number and user input number
for(int i = 0; i < listOfBooks.length - 1; i++) {
if (listOfBooks.get(i) == number) {
txtLinearOutput.setText(listOfBooks[i]);
break;
}
}
*There is a problem with the listOfBooks.get in the if statement. Also I need to apply a binary search that would search the same array just using the binary method. Need help to apply this type of binary search.
How could I make a statement that checks if the int number is equal to an index?
Note that the following code is just an example of what I have to apply. Variables are all for example purposes:
public static Boolean binarySearch(String [ ] A, int left, int right, String V){
int middle;
if (left > right) {
return false;
}
middle = (left + right)/2;
int compare = V.compareTo(A[middle]);
if (compare == 0) {
return true;
}
if (compare < 0) {
return binarySearch(A, left, middle-1, V);
} else {
return binarySearch(A, middle + 1, right, V);
}
}
you can avoid for loop and check condition by just giving number like this: txtLinearOutput.setText(listOfBooks[number-1]);
remove your code
// Linear search to match index number and user input number
for(int i = 0; i < listOfBooks.length - 1; i++) {
if (listOfBooks.get(i) == number) {
txtLinearOutput.setText(listOfBooks[i]);
break;
}
with
try{
int number = Integer.parseInt(numberInput);
if(number>0 && number<101){
txtLinearOutput.setText(listOfBooks[number-1]);
}else{
// out of range
}
}catch(Exception e){
// handle exception here
}
You are comparing if (listOfBooks.get(i) == number) it is wrong, you should compare: if (i == number), becouse you need compare element position.
This isn't a binary search answer. Just an implementation of HashMap. Have a look at it.
HashMap<String, Integer> books = new HashMap();
books.put("abc", 1);
books.put("xyz", 2);
books.put("pqr", 3);
books.put("lmo", 4);
System.out.println(books.getValue("abc");
Using the inbuilt BinarySearch.
String []arr = new String[15];
arr[0] = "abc";
arr[5] = "prq";
arr[7] = "lmo";
arr[10] = "xyz";
System.out.println(Arrays.binarySearch(arr, "lmo"));
How to compare Strings using binary search.
String[] array = new String[4];
array[0] = "abc";
array[1] = "lmo";
array[2] = "pqr";
array[3] = "xyz";
int first, last, middle;
first = 0;
last = array.length - 1;
middle = (first + last) / 2;
String key = "abc";
while (first <= last) {
if (compare(array[middle], key))
first = middle + 1;
else if (array[middle].equals(key)) {
System.out.println(key + " found at location " + (middle) + ".");
break;
} else {
last = middle - 1;
}
middle = (first + last) / 2;
}
if (first > last)
System.out.println(key + " is not found.\n");
}
private static boolean compare(String string, String key) {
// TODO Auto-generated method stub
for (int i = 0; i < Math.min(string.length(), key.length()); ++i)
if (string.charAt(i) < key.charAt(i))
return true;
return false;
}
Your linear search code looks something like this
try{
txtLinearOutput.setText(listOfBooks[yourNumber]);
}
catch(IndexOutOfBoundsException ie){
// prompt that number is not an index
}
catch(Exception e){
// if any other exception is caught
}
What you are doing here:
if (listOfBooks.get(i) == number) {
is that you are matching the content of the array with the input number, which is irrelevant.
You can directly use the input number to fetch the value stored at the index.
For example:
txtLinearOutput.setText(listOfBooks[number-1]);
Additionally, int number = Integer.parseInt(numberInput); should be placed within try-catch block to validate input number parsing. And you can check if the input number is within the range of the array to avoid exceptions like:
try{
int number = Integer.parseInt(numberInput);
// Linear search to match index number and user input number
if (number > 0 && number <=100) {
txtLinearOutput.setText(listOfBooks[number-1]);
} else {
// Display error message
}
} catch(Exception e) {
// Handle exception and display error message
}
And for using binary search, the string array need to be sorted. You can use Arrays.sort() method for sorting it.
And regarding using binary search, you can use Java Arrays Binary Search method

Apply a Frequency to an Element in an Array

I am trying to make a script that will take a set of Words (custom class), organize them alphabetically into an array by their text value (this part works). From here I was going to count how many terms ahead of it are the same as it, and that will be the frequency for all those similar terms. Then it continues to do this till each element in the array has been assigned a frequency. From here it re sorts the elements back into their original position provided a pre stored variable that holds their original element order. Here is the code:
public void setFrequencies() {
List<Word> dupeWordList;
dupeWordList = new ArrayList<>(wordList);
dupeWordList.removeAll(Collections.singleton(null));
Collections.sort(dupeWordList, (Word one, Word other) -> one.getValue().compareTo(other.getValue()));
int count;
int currElement;
for(currElement = 0; currElement < dupeWordList.size(); currElement++) {
count = 1;
Word tempWord = dupeWordList.get(currElement);
tempWord.setFrequency(count);
if(currElement+1 <= dupeWordList.size() - 1) {
Word nextWord = dupeWordList.get(currElement+1);
while(tempWord.getValue().equals(nextWord.getValue())) {
count++;
currElement++;
tempWord.setFrequency(count);
for(int e = 0; e < count - 1; e++) {
Word middleWord = new Word();
if(currElement-count+2+e < dupeWordList.size() - 1) {
middleWord = dupeWordList.get(currElement-count+2+e);
}
middleWord.setFrequency(count);
}
if(currElement+1 <= dupeWordList.size() - 1) {
nextWord = dupeWordList.get(currElement+1);
} else {
break;
}
}
break;
}
}
List<Word> reSortedList = new ArrayList<>(wordList);
Word fillWord = new Word();
fillWord.setFrequency(0);
fillWord.setValue(null);
Collections.fill(reSortedList, fillWord);
for(int i = 0; i < dupeWordList.size(); i++) {
Word word = dupeWordList.get(i);
int wordOrder = word.getOrigOrder();
reSortedList.set(wordOrder, word);
}
System.out.println(Arrays.toString(DebugFreq(reSortedList)));
setWordList(reSortedList);
}
public int[] DebugFreq(List<Word> rSL) {
int[] results = new int[rSL.size()];
for(int i=0; i < results.length; i++) {
results[i] = rSL.get(i).getFrequency();
}
return results;
}
As you can see I set up a little debug method at the bottom. When I run this method is shows that every word was given a frequency of 1. I cant see the issue in my code, nor does it get any errors. Keep in mind I have had it display the sorted dupeWordList and it does correctly alphabetize and their are consecutive duplicate elements in it so this should not be happening.
So If I understand you correctly.. below code would be your solution.
Okay You have a list which is having a strings (terms or words) which are sorted in alphabetical Order.
// Okay the below list is already sorted in alphabetical order.
List<String> dupeWordList = new ArrayList<>(wordList);
To count the Frequency of words in your list, Map<String, Integer> might help you as below.
//Take a Map with Integer as value and String as key.
Map<String,Integer> result = new HashMap<String,Integer> ();
//Iterate your List
for(String s : dupeWordList)
{
if(map.containskey(s))
{
map.put(s,map.get(s)+1);
// Please consider casting here.
}else
{
map.put(s,1);
}
}
Okay now we have a map which is having the frequency of your words or terms as value in your map.
Hope it helps.

Java - removing object from Array

I need to create a method to remove an element from an array of objects, without turning it into an ArrayList.
This is the constructor for my object:
public Person(String name1, String telno1)
{
name = name1;
telno = telno1;
}
And my Array:
int capacity = 100;
private Person[] thePhonebook = new Person[capacity];
And i have a shell for my remove method:
public String removeEntry(String name)
{
//name is name of the person to be removed (dont worry about duplicate names)
//returns the telephone number of removed entry
}
Im not sure how to delete the element in the array (i dont want to just set the values to null)
I did think of creating a new array and copying parts on either side of the element to be removed to form a new array but im not sure how to implement that.
I also have a find method which can be used to find the name of the person in the array if that helps:
private int find(String name)
{
String name1 = name;
int i = 0;
int elementNo = 0;
int found = 0;
while(i < size)
{
if(thePhonebook[i].getName().equals(name1))
{
elementNo = i;
found = 1;
break;
}
}
if(found == 1)
{
return dirNo;
}
else
{
dirNo = -1;
return dirNo;
}
}
Thanks for your time.
You cannot directly remove an element from an array in Java. You two choices:
A. If you must preserve the order of the elements in the array: Begin at the index you want to remove, and shift each element "down" one index (toward index 0), as in:
public String removeEntry(String name)
{
String result = null;
int index = find(name);
if (index >= 0)
{
result = thePhonebook[index].telno;
for (int i = index + 1; i < thePhonebook.length; ++i)
{
thePhonebook[i - 1] = thePhonebook[i];
if (thePhonebook[i] == null)
{
break;
}
}
thePhonebook[thePhonebook.length - 1] = null;
}
return result;
}
In the above implementation, the value null in the array signifies the end of the list.
B. If the order of the elements in the array doesn't matter: Swap the element you want to remove with the last element of the list. Note that to do this you need to maintain a length value for the list, which is the value thePhonebookLength in the code below.
public String removeEntry(String name)
{
String result = null;
int index = find(name);
if (index >= 0)
{
result = thePhonebook[index].telno;
thePhonebook[index] = thePhonebook[thePhonebookLength - 1];
thePhonebook[--thePhonebookLength] = null;
}
return result;
}
A benefit of both of these solutions is that the array is modified in place, without using allocation.
Having offered these possibilities, I suggest that using a collection is better suited for your purposes -- such as one of the List subclasses, or perhaps even a Map if lookups by name are common.
To do this is to get the last index in your array and then pass it to the one that was just deleted and the delete the last array.. if the array is the last one dont it just delete it..
for(int i = 0; i < thePhonebook .length; i++)
{
if(thePhonebook[i].getName().equals(string))
{
if(i == thePhonebook .length - 1)
thePhonebook[i] = null;
else
{
thePhonebook[i] = null;
thePhonebook[i] = thePhonebook[thePhonebook .length - 1];
thePhonebook[thePhonebook .length - 1] = null;
}
}
}

Categories