how to input values into ArrayList alphabeticallyIs Java “pass-by-reference” or “pass-by-value”?Create ArrayList from arrayHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How to get an enum value from a string value in Java?How to get the last value of an ArrayListInitialization of an ArrayList in one lineHow do I determine whether an array contains a particular value in Java?Converting 'ArrayList<String> to 'String[]' in JavaConvert ArrayList<String> to String[] array
First Program Tic-Tac-Toe
How do I disable login of user?
Are there any German nonsense poems (Jabberwocky)?
Why would a rational buyer offer to buy with no conditions precedent?
Are black holes spherical during merger?
How to melt snow without fire or body heat?
Drums and punctuation
Manager questioning my time estimates for a project
Gravitational Force Between Numbers
Job Market: should one hide their (young) age?
I know that there is a preselected candidate for a position to be filled at my department. What should I do?
Why did Theresa May offer a vote on a second Brexit referendum?
Time complexity of an algorithm: Is it important to state the base of the logarithm?
Navigating a quick return to previous employer
Where is Jon going?
Heat lost in ideal capacitor charging
A Multitude Of Mates In 5-An Original Chess Puzzle
How to politely tell someone they did not hit "reply to all" in an email?
Expected maximum number of unpaired socks
Did this character show any indication of wanting to rule before S8E6?
Beginner looking to learn/master musical theory and instrumental ability. Where should I begin?
When playing Edgar Markov, what is the definition of a "Vampire spell"?
Shorten or merge multiple lines of `&> /dev/null &`
Of strange atmospheres - the survivable but unbreathable
how to input values into ArrayList alphabetically
Is Java “pass-by-reference” or “pass-by-value”?Create ArrayList from arrayHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How to get an enum value from a string value in Java?How to get the last value of an ArrayListInitialization of an ArrayList in one lineHow do I determine whether an array contains a particular value in Java?Converting 'ArrayList<String> to 'String[]' in JavaConvert ArrayList<String> to String[] array
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm given the task of adding a value into an ArrayList alphabetically (by lastname first, and firstname if lastnames are the same),I'm not allowed to sort the ArrayList once all the inputs are given. What I am suppose to do is determine the location of where the value should be each time an input is given and place it there. Example values: Inputs are John Doe, Bryan Sully, Harry Ache, Ali Doe, Bry Dyre , Output should be Harry Ache, Ali Doe, John Doe, Bry Dyre, Bryan Sully. However, in cases where there are two of the same last names, what will occur is Harry Ache, Ali Doe, Bry Dyre, John Doe, Bryan Sully, why?
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
if(list.size() == 0)
list.add(p);
else
for(Person pp: list)
int getIndex = list.indexOf(pp);
int lOrder = p.getLastName().compareTo(pp.getLastName());
if(lOrder > 0)
list.add(getIndex + 1, p);
break;
else if(lOrder == 0)
int fOrder = p.getFirstName().compareTo(pp.getFirstName());
if(fOrder > 0)
list.add(getIndex, p);
break;
else
list.add(getIndex + 1, p);
break;
else
list.add(getIndex, p);
break;
java arraylist
add a comment |
I'm given the task of adding a value into an ArrayList alphabetically (by lastname first, and firstname if lastnames are the same),I'm not allowed to sort the ArrayList once all the inputs are given. What I am suppose to do is determine the location of where the value should be each time an input is given and place it there. Example values: Inputs are John Doe, Bryan Sully, Harry Ache, Ali Doe, Bry Dyre , Output should be Harry Ache, Ali Doe, John Doe, Bry Dyre, Bryan Sully. However, in cases where there are two of the same last names, what will occur is Harry Ache, Ali Doe, Bry Dyre, John Doe, Bryan Sully, why?
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
if(list.size() == 0)
list.add(p);
else
for(Person pp: list)
int getIndex = list.indexOf(pp);
int lOrder = p.getLastName().compareTo(pp.getLastName());
if(lOrder > 0)
list.add(getIndex + 1, p);
break;
else if(lOrder == 0)
int fOrder = p.getFirstName().compareTo(pp.getFirstName());
if(fOrder > 0)
list.add(getIndex, p);
break;
else
list.add(getIndex + 1, p);
break;
else
list.add(getIndex, p);
break;
java arraylist
2
Exactly what “certain circumstances” cause the problem? Please provide a MCVE. Also, see insertion sort.
– Bohemian♦
Mar 24 at 0:07
1
I recommend you to implement the Comparable interface in your Person class in order to implement your own comparison algorithm (firstname then lastname). This will allow you to compare Person objects directly and will make your code easier to read.
– Hichem BOUSSETTA
Mar 24 at 0:12
@Bohemian as now stated in the question, in cases where there are two of the same last names, the last names will not be together but rather there is a split.
– Urmzd
Mar 24 at 0:27
add a comment |
I'm given the task of adding a value into an ArrayList alphabetically (by lastname first, and firstname if lastnames are the same),I'm not allowed to sort the ArrayList once all the inputs are given. What I am suppose to do is determine the location of where the value should be each time an input is given and place it there. Example values: Inputs are John Doe, Bryan Sully, Harry Ache, Ali Doe, Bry Dyre , Output should be Harry Ache, Ali Doe, John Doe, Bry Dyre, Bryan Sully. However, in cases where there are two of the same last names, what will occur is Harry Ache, Ali Doe, Bry Dyre, John Doe, Bryan Sully, why?
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
if(list.size() == 0)
list.add(p);
else
for(Person pp: list)
int getIndex = list.indexOf(pp);
int lOrder = p.getLastName().compareTo(pp.getLastName());
if(lOrder > 0)
list.add(getIndex + 1, p);
break;
else if(lOrder == 0)
int fOrder = p.getFirstName().compareTo(pp.getFirstName());
if(fOrder > 0)
list.add(getIndex, p);
break;
else
list.add(getIndex + 1, p);
break;
else
list.add(getIndex, p);
break;
java arraylist
I'm given the task of adding a value into an ArrayList alphabetically (by lastname first, and firstname if lastnames are the same),I'm not allowed to sort the ArrayList once all the inputs are given. What I am suppose to do is determine the location of where the value should be each time an input is given and place it there. Example values: Inputs are John Doe, Bryan Sully, Harry Ache, Ali Doe, Bry Dyre , Output should be Harry Ache, Ali Doe, John Doe, Bry Dyre, Bryan Sully. However, in cases where there are two of the same last names, what will occur is Harry Ache, Ali Doe, Bry Dyre, John Doe, Bryan Sully, why?
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
if(list.size() == 0)
list.add(p);
else
for(Person pp: list)
int getIndex = list.indexOf(pp);
int lOrder = p.getLastName().compareTo(pp.getLastName());
if(lOrder > 0)
list.add(getIndex + 1, p);
break;
else if(lOrder == 0)
int fOrder = p.getFirstName().compareTo(pp.getFirstName());
if(fOrder > 0)
list.add(getIndex, p);
break;
else
list.add(getIndex + 1, p);
break;
else
list.add(getIndex, p);
break;
java arraylist
java arraylist
edited Mar 24 at 0:26
Urmzd
asked Mar 24 at 0:01
UrmzdUrmzd
135
135
2
Exactly what “certain circumstances” cause the problem? Please provide a MCVE. Also, see insertion sort.
– Bohemian♦
Mar 24 at 0:07
1
I recommend you to implement the Comparable interface in your Person class in order to implement your own comparison algorithm (firstname then lastname). This will allow you to compare Person objects directly and will make your code easier to read.
– Hichem BOUSSETTA
Mar 24 at 0:12
@Bohemian as now stated in the question, in cases where there are two of the same last names, the last names will not be together but rather there is a split.
– Urmzd
Mar 24 at 0:27
add a comment |
2
Exactly what “certain circumstances” cause the problem? Please provide a MCVE. Also, see insertion sort.
– Bohemian♦
Mar 24 at 0:07
1
I recommend you to implement the Comparable interface in your Person class in order to implement your own comparison algorithm (firstname then lastname). This will allow you to compare Person objects directly and will make your code easier to read.
– Hichem BOUSSETTA
Mar 24 at 0:12
@Bohemian as now stated in the question, in cases where there are two of the same last names, the last names will not be together but rather there is a split.
– Urmzd
Mar 24 at 0:27
2
2
Exactly what “certain circumstances” cause the problem? Please provide a MCVE. Also, see insertion sort.
– Bohemian♦
Mar 24 at 0:07
Exactly what “certain circumstances” cause the problem? Please provide a MCVE. Also, see insertion sort.
– Bohemian♦
Mar 24 at 0:07
1
1
I recommend you to implement the Comparable interface in your Person class in order to implement your own comparison algorithm (firstname then lastname). This will allow you to compare Person objects directly and will make your code easier to read.
– Hichem BOUSSETTA
Mar 24 at 0:12
I recommend you to implement the Comparable interface in your Person class in order to implement your own comparison algorithm (firstname then lastname). This will allow you to compare Person objects directly and will make your code easier to read.
– Hichem BOUSSETTA
Mar 24 at 0:12
@Bohemian as now stated in the question, in cases where there are two of the same last names, the last names will not be together but rather there is a split.
– Urmzd
Mar 24 at 0:27
@Bohemian as now stated in the question, in cases where there are two of the same last names, the last names will not be together but rather there is a split.
– Urmzd
Mar 24 at 0:27
add a comment |
3 Answers
3
active
oldest
votes
One issue with your code is that you are making an insertion after a single iteration of your loop, inserting Person p only in comparison to the first Person in the list.
Here is an improved implementation:
public void addPerson(Person person)
if (list.isEmpty())
list.add(p);
else
// the position where you will insert the Person;
// default value is list.size(), so it can be added to the end
int position = list.size();
Person p;
for (int i = 0; i < list.size(); i++)
p = list.get(i);
// if the comparison result is > 0, you found the first Person
// in the list that comes alphabetically after;
// Insert person before it, at position i
if (compare(p, person) > 0)
position = i;
break; // only break now that you've found the insert position
list.add(person, position);
/**
* @return 0 if both Persons p1 & p2 have the same names,
* a positive number if p1 is lexicographically greater than p2,
* or a negative number if p1 is lexicographically less than p2
*/
private int compare(Person p1, Person p2)
int result = p1.getLastName().compareTo(p2.getLastName());
if (result == 0)
result = p1.getFirstName().compareTo(p2.getFirstName());
return result;
As others suggested, implementing the Comparable interface in Person if possible can also help create a cleaner implementation.
add a comment |
Few improvements.
You are better off if you can iterate the list using the index like
for(int i = 0; i < array.size(); i++)You need not have to check for
lastNameandfirstNameseparately. You can just compare both of them together(p.lastName + p.firstName).compareTo(pp.lastName + pp.firstName)and act upon the result. As you already have the index of the current element, you just have to check if you just insert the new item on the same index or not.
Here is a sample implementation
static void addPerson(Person person)
for (int i = 0; i < sortedList.size(); i++)
var existingPerson = sortedList.get(i);
var compareResult = compare(existingPerson, person);
if (compareResult > 0)
sortedList.add(i, person);
return;
sortedList.add(person);
static int compare(Person p1, Person p2)
return (p1.lastName + p1.firstName).compareTo(p2.lastName + p2.firstName);
Thank you for the new idea. However, as part of the question requirement, I must compare the last name first and compare the first name only if the last names are the same. I understand that this is strange, but unfortunately that's how it is.
– Urmzd
Mar 24 at 1:24
add a comment |
The problem with your algorithm, is that you always looking at the first person in the target list, and making decisions solely on that person, notice how all your "branches" have a break statement at the end?
I understand your "reason" for adding all those break statements, those make sure the new person always gets inserted into the list, when it doesn't match, the same reason why your first check if the list is empty.
To properly implement an "insertion sort" system, you actually need to loop over all the indexes of your list.
An simple "insertion sort" algorithm looks like this:
- Loop over the target list
- Check if existing entry is "bigger" than the newly person
- If the existing entry is bigger, we need to move that entry (all all remaining entries) up 1 spot, insert out entry, and abort
- If we are done looping, and we didn't abort in the above steps, insert our entry at the end of the list.
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
// Loop
int size = list.size();
for(int getIndex = 0; getIndex < size; getIndex++)
Person pp = list.get(getIndex);
// Compare
int compare = p.getLastName().compareTo(pp.getLastName());
if (compare > 0)
continue;
else if(compare == 0)
if (p.getFirstName().compareTo(pp.getFirstName()) > 0)
continue;
// Add in existing slot
list.add(getIndex, p);
return;
// Add at the end
list.add(p);
One hard part of this, is the fact that we have to compare on 2 things for a single person, this makes the compare logic way harder than it needs to be. This can be solved by factoring this part out to a "helper" comparator that does this logic merging for us:
Comparator<Person> compare = Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName);
// Then, inside the above loop:
...
// Compare
if (compare.compare(p, pp) > 0)
continue;
...
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55319516%2fhow-to-input-values-into-arraylist-alphabetically%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
One issue with your code is that you are making an insertion after a single iteration of your loop, inserting Person p only in comparison to the first Person in the list.
Here is an improved implementation:
public void addPerson(Person person)
if (list.isEmpty())
list.add(p);
else
// the position where you will insert the Person;
// default value is list.size(), so it can be added to the end
int position = list.size();
Person p;
for (int i = 0; i < list.size(); i++)
p = list.get(i);
// if the comparison result is > 0, you found the first Person
// in the list that comes alphabetically after;
// Insert person before it, at position i
if (compare(p, person) > 0)
position = i;
break; // only break now that you've found the insert position
list.add(person, position);
/**
* @return 0 if both Persons p1 & p2 have the same names,
* a positive number if p1 is lexicographically greater than p2,
* or a negative number if p1 is lexicographically less than p2
*/
private int compare(Person p1, Person p2)
int result = p1.getLastName().compareTo(p2.getLastName());
if (result == 0)
result = p1.getFirstName().compareTo(p2.getFirstName());
return result;
As others suggested, implementing the Comparable interface in Person if possible can also help create a cleaner implementation.
add a comment |
One issue with your code is that you are making an insertion after a single iteration of your loop, inserting Person p only in comparison to the first Person in the list.
Here is an improved implementation:
public void addPerson(Person person)
if (list.isEmpty())
list.add(p);
else
// the position where you will insert the Person;
// default value is list.size(), so it can be added to the end
int position = list.size();
Person p;
for (int i = 0; i < list.size(); i++)
p = list.get(i);
// if the comparison result is > 0, you found the first Person
// in the list that comes alphabetically after;
// Insert person before it, at position i
if (compare(p, person) > 0)
position = i;
break; // only break now that you've found the insert position
list.add(person, position);
/**
* @return 0 if both Persons p1 & p2 have the same names,
* a positive number if p1 is lexicographically greater than p2,
* or a negative number if p1 is lexicographically less than p2
*/
private int compare(Person p1, Person p2)
int result = p1.getLastName().compareTo(p2.getLastName());
if (result == 0)
result = p1.getFirstName().compareTo(p2.getFirstName());
return result;
As others suggested, implementing the Comparable interface in Person if possible can also help create a cleaner implementation.
add a comment |
One issue with your code is that you are making an insertion after a single iteration of your loop, inserting Person p only in comparison to the first Person in the list.
Here is an improved implementation:
public void addPerson(Person person)
if (list.isEmpty())
list.add(p);
else
// the position where you will insert the Person;
// default value is list.size(), so it can be added to the end
int position = list.size();
Person p;
for (int i = 0; i < list.size(); i++)
p = list.get(i);
// if the comparison result is > 0, you found the first Person
// in the list that comes alphabetically after;
// Insert person before it, at position i
if (compare(p, person) > 0)
position = i;
break; // only break now that you've found the insert position
list.add(person, position);
/**
* @return 0 if both Persons p1 & p2 have the same names,
* a positive number if p1 is lexicographically greater than p2,
* or a negative number if p1 is lexicographically less than p2
*/
private int compare(Person p1, Person p2)
int result = p1.getLastName().compareTo(p2.getLastName());
if (result == 0)
result = p1.getFirstName().compareTo(p2.getFirstName());
return result;
As others suggested, implementing the Comparable interface in Person if possible can also help create a cleaner implementation.
One issue with your code is that you are making an insertion after a single iteration of your loop, inserting Person p only in comparison to the first Person in the list.
Here is an improved implementation:
public void addPerson(Person person)
if (list.isEmpty())
list.add(p);
else
// the position where you will insert the Person;
// default value is list.size(), so it can be added to the end
int position = list.size();
Person p;
for (int i = 0; i < list.size(); i++)
p = list.get(i);
// if the comparison result is > 0, you found the first Person
// in the list that comes alphabetically after;
// Insert person before it, at position i
if (compare(p, person) > 0)
position = i;
break; // only break now that you've found the insert position
list.add(person, position);
/**
* @return 0 if both Persons p1 & p2 have the same names,
* a positive number if p1 is lexicographically greater than p2,
* or a negative number if p1 is lexicographically less than p2
*/
private int compare(Person p1, Person p2)
int result = p1.getLastName().compareTo(p2.getLastName());
if (result == 0)
result = p1.getFirstName().compareTo(p2.getFirstName());
return result;
As others suggested, implementing the Comparable interface in Person if possible can also help create a cleaner implementation.
answered Mar 24 at 16:06
D. PereiraD. Pereira
1015
1015
add a comment |
add a comment |
Few improvements.
You are better off if you can iterate the list using the index like
for(int i = 0; i < array.size(); i++)You need not have to check for
lastNameandfirstNameseparately. You can just compare both of them together(p.lastName + p.firstName).compareTo(pp.lastName + pp.firstName)and act upon the result. As you already have the index of the current element, you just have to check if you just insert the new item on the same index or not.
Here is a sample implementation
static void addPerson(Person person)
for (int i = 0; i < sortedList.size(); i++)
var existingPerson = sortedList.get(i);
var compareResult = compare(existingPerson, person);
if (compareResult > 0)
sortedList.add(i, person);
return;
sortedList.add(person);
static int compare(Person p1, Person p2)
return (p1.lastName + p1.firstName).compareTo(p2.lastName + p2.firstName);
Thank you for the new idea. However, as part of the question requirement, I must compare the last name first and compare the first name only if the last names are the same. I understand that this is strange, but unfortunately that's how it is.
– Urmzd
Mar 24 at 1:24
add a comment |
Few improvements.
You are better off if you can iterate the list using the index like
for(int i = 0; i < array.size(); i++)You need not have to check for
lastNameandfirstNameseparately. You can just compare both of them together(p.lastName + p.firstName).compareTo(pp.lastName + pp.firstName)and act upon the result. As you already have the index of the current element, you just have to check if you just insert the new item on the same index or not.
Here is a sample implementation
static void addPerson(Person person)
for (int i = 0; i < sortedList.size(); i++)
var existingPerson = sortedList.get(i);
var compareResult = compare(existingPerson, person);
if (compareResult > 0)
sortedList.add(i, person);
return;
sortedList.add(person);
static int compare(Person p1, Person p2)
return (p1.lastName + p1.firstName).compareTo(p2.lastName + p2.firstName);
Thank you for the new idea. However, as part of the question requirement, I must compare the last name first and compare the first name only if the last names are the same. I understand that this is strange, but unfortunately that's how it is.
– Urmzd
Mar 24 at 1:24
add a comment |
Few improvements.
You are better off if you can iterate the list using the index like
for(int i = 0; i < array.size(); i++)You need not have to check for
lastNameandfirstNameseparately. You can just compare both of them together(p.lastName + p.firstName).compareTo(pp.lastName + pp.firstName)and act upon the result. As you already have the index of the current element, you just have to check if you just insert the new item on the same index or not.
Here is a sample implementation
static void addPerson(Person person)
for (int i = 0; i < sortedList.size(); i++)
var existingPerson = sortedList.get(i);
var compareResult = compare(existingPerson, person);
if (compareResult > 0)
sortedList.add(i, person);
return;
sortedList.add(person);
static int compare(Person p1, Person p2)
return (p1.lastName + p1.firstName).compareTo(p2.lastName + p2.firstName);
Few improvements.
You are better off if you can iterate the list using the index like
for(int i = 0; i < array.size(); i++)You need not have to check for
lastNameandfirstNameseparately. You can just compare both of them together(p.lastName + p.firstName).compareTo(pp.lastName + pp.firstName)and act upon the result. As you already have the index of the current element, you just have to check if you just insert the new item on the same index or not.
Here is a sample implementation
static void addPerson(Person person)
for (int i = 0; i < sortedList.size(); i++)
var existingPerson = sortedList.get(i);
var compareResult = compare(existingPerson, person);
if (compareResult > 0)
sortedList.add(i, person);
return;
sortedList.add(person);
static int compare(Person p1, Person p2)
return (p1.lastName + p1.firstName).compareTo(p2.lastName + p2.firstName);
answered Mar 24 at 0:57
Abhijith NagarajanAbhijith Nagarajan
3,0871422
3,0871422
Thank you for the new idea. However, as part of the question requirement, I must compare the last name first and compare the first name only if the last names are the same. I understand that this is strange, but unfortunately that's how it is.
– Urmzd
Mar 24 at 1:24
add a comment |
Thank you for the new idea. However, as part of the question requirement, I must compare the last name first and compare the first name only if the last names are the same. I understand that this is strange, but unfortunately that's how it is.
– Urmzd
Mar 24 at 1:24
Thank you for the new idea. However, as part of the question requirement, I must compare the last name first and compare the first name only if the last names are the same. I understand that this is strange, but unfortunately that's how it is.
– Urmzd
Mar 24 at 1:24
Thank you for the new idea. However, as part of the question requirement, I must compare the last name first and compare the first name only if the last names are the same. I understand that this is strange, but unfortunately that's how it is.
– Urmzd
Mar 24 at 1:24
add a comment |
The problem with your algorithm, is that you always looking at the first person in the target list, and making decisions solely on that person, notice how all your "branches" have a break statement at the end?
I understand your "reason" for adding all those break statements, those make sure the new person always gets inserted into the list, when it doesn't match, the same reason why your first check if the list is empty.
To properly implement an "insertion sort" system, you actually need to loop over all the indexes of your list.
An simple "insertion sort" algorithm looks like this:
- Loop over the target list
- Check if existing entry is "bigger" than the newly person
- If the existing entry is bigger, we need to move that entry (all all remaining entries) up 1 spot, insert out entry, and abort
- If we are done looping, and we didn't abort in the above steps, insert our entry at the end of the list.
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
// Loop
int size = list.size();
for(int getIndex = 0; getIndex < size; getIndex++)
Person pp = list.get(getIndex);
// Compare
int compare = p.getLastName().compareTo(pp.getLastName());
if (compare > 0)
continue;
else if(compare == 0)
if (p.getFirstName().compareTo(pp.getFirstName()) > 0)
continue;
// Add in existing slot
list.add(getIndex, p);
return;
// Add at the end
list.add(p);
One hard part of this, is the fact that we have to compare on 2 things for a single person, this makes the compare logic way harder than it needs to be. This can be solved by factoring this part out to a "helper" comparator that does this logic merging for us:
Comparator<Person> compare = Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName);
// Then, inside the above loop:
...
// Compare
if (compare.compare(p, pp) > 0)
continue;
...
add a comment |
The problem with your algorithm, is that you always looking at the first person in the target list, and making decisions solely on that person, notice how all your "branches" have a break statement at the end?
I understand your "reason" for adding all those break statements, those make sure the new person always gets inserted into the list, when it doesn't match, the same reason why your first check if the list is empty.
To properly implement an "insertion sort" system, you actually need to loop over all the indexes of your list.
An simple "insertion sort" algorithm looks like this:
- Loop over the target list
- Check if existing entry is "bigger" than the newly person
- If the existing entry is bigger, we need to move that entry (all all remaining entries) up 1 spot, insert out entry, and abort
- If we are done looping, and we didn't abort in the above steps, insert our entry at the end of the list.
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
// Loop
int size = list.size();
for(int getIndex = 0; getIndex < size; getIndex++)
Person pp = list.get(getIndex);
// Compare
int compare = p.getLastName().compareTo(pp.getLastName());
if (compare > 0)
continue;
else if(compare == 0)
if (p.getFirstName().compareTo(pp.getFirstName()) > 0)
continue;
// Add in existing slot
list.add(getIndex, p);
return;
// Add at the end
list.add(p);
One hard part of this, is the fact that we have to compare on 2 things for a single person, this makes the compare logic way harder than it needs to be. This can be solved by factoring this part out to a "helper" comparator that does this logic merging for us:
Comparator<Person> compare = Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName);
// Then, inside the above loop:
...
// Compare
if (compare.compare(p, pp) > 0)
continue;
...
add a comment |
The problem with your algorithm, is that you always looking at the first person in the target list, and making decisions solely on that person, notice how all your "branches" have a break statement at the end?
I understand your "reason" for adding all those break statements, those make sure the new person always gets inserted into the list, when it doesn't match, the same reason why your first check if the list is empty.
To properly implement an "insertion sort" system, you actually need to loop over all the indexes of your list.
An simple "insertion sort" algorithm looks like this:
- Loop over the target list
- Check if existing entry is "bigger" than the newly person
- If the existing entry is bigger, we need to move that entry (all all remaining entries) up 1 spot, insert out entry, and abort
- If we are done looping, and we didn't abort in the above steps, insert our entry at the end of the list.
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
// Loop
int size = list.size();
for(int getIndex = 0; getIndex < size; getIndex++)
Person pp = list.get(getIndex);
// Compare
int compare = p.getLastName().compareTo(pp.getLastName());
if (compare > 0)
continue;
else if(compare == 0)
if (p.getFirstName().compareTo(pp.getFirstName()) > 0)
continue;
// Add in existing slot
list.add(getIndex, p);
return;
// Add at the end
list.add(p);
One hard part of this, is the fact that we have to compare on 2 things for a single person, this makes the compare logic way harder than it needs to be. This can be solved by factoring this part out to a "helper" comparator that does this logic merging for us:
Comparator<Person> compare = Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName);
// Then, inside the above loop:
...
// Compare
if (compare.compare(p, pp) > 0)
continue;
...
The problem with your algorithm, is that you always looking at the first person in the target list, and making decisions solely on that person, notice how all your "branches" have a break statement at the end?
I understand your "reason" for adding all those break statements, those make sure the new person always gets inserted into the list, when it doesn't match, the same reason why your first check if the list is empty.
To properly implement an "insertion sort" system, you actually need to loop over all the indexes of your list.
An simple "insertion sort" algorithm looks like this:
- Loop over the target list
- Check if existing entry is "bigger" than the newly person
- If the existing entry is bigger, we need to move that entry (all all remaining entries) up 1 spot, insert out entry, and abort
- If we are done looping, and we didn't abort in the above steps, insert our entry at the end of the list.
ArrayList<Person> list = new ArrayList<Person>();
public void addPerson(Person p)
// Loop
int size = list.size();
for(int getIndex = 0; getIndex < size; getIndex++)
Person pp = list.get(getIndex);
// Compare
int compare = p.getLastName().compareTo(pp.getLastName());
if (compare > 0)
continue;
else if(compare == 0)
if (p.getFirstName().compareTo(pp.getFirstName()) > 0)
continue;
// Add in existing slot
list.add(getIndex, p);
return;
// Add at the end
list.add(p);
One hard part of this, is the fact that we have to compare on 2 things for a single person, this makes the compare logic way harder than it needs to be. This can be solved by factoring this part out to a "helper" comparator that does this logic merging for us:
Comparator<Person> compare = Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName);
// Then, inside the above loop:
...
// Compare
if (compare.compare(p, pp) > 0)
continue;
...
answered Mar 24 at 17:00
FerrybigFerrybig
12.5k53755
12.5k53755
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55319516%2fhow-to-input-values-into-arraylist-alphabetically%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Exactly what “certain circumstances” cause the problem? Please provide a MCVE. Also, see insertion sort.
– Bohemian♦
Mar 24 at 0:07
1
I recommend you to implement the Comparable interface in your Person class in order to implement your own comparison algorithm (firstname then lastname). This will allow you to compare Person objects directly and will make your code easier to read.
– Hichem BOUSSETTA
Mar 24 at 0:12
@Bohemian as now stated in the question, in cases where there are two of the same last names, the last names will not be together but rather there is a split.
– Urmzd
Mar 24 at 0:27