arraylist.get(i)= arraylist.get(i);
arraylist.get(j) =tmp;

You can't assign a value to a method call. As the compiler told you, the left hand side of an assignment must be a variable.

Use set method :

arraylist.set(i,arraylist.get(j));
arraylist.set(j,tmp);

Is there a way to do it without using set method?

No. Unless you wish to convert your ArrayList to an array, sort the array, and update the ArrayList with the sorted array.

Answer from Eran on Stack Overflow
🌐
Blogger
javarevisited.blogspot.com › 2023 › 09 › how-to-sort-arraylist-in-java-without.html
3 ways to sort an ArrayList in Java without using sort() method - Example Tutorial
September 24, 2023 - You can use any sorting algorithm like bubble sort, insertion sort, selection sort, quicksort, or merge sort to sort your ArrayList without using sort() method from Collection API.
Discussions

java - Sorting a list without using the Collection methods - Stack Overflow
How do I sort a list without using the Collection methods? More on stackoverflow.com
🌐 stackoverflow.com
May 16, 2010
How can I get Sorted List behavior in Java without using Collections.sort()? - Stack Overflow
I understand that Java does not possess a Sorted List for various conceptual reasons, but consider the case I need to have a collection which is kind of like a Priority Queue but also allows me ran... More on stackoverflow.com
🌐 stackoverflow.com
Sorting array list without using .sort in Java
Note: You don’t need to use Arrays.sort or Collections.sort for solving this task. In fact, using these sorting libraries can make your code inefficient. What this is suggesting is that you don't need to sort the whole list (using a premade or your own sorting algorithm) at any point. Instead, you maintain the list in decreasing order all the time. So always when adding items to the bag, you iterate the existing items and insert the new item in the correct position according to the wanted order. More on reddit.com
🌐 r/learnjava
2
1
October 2, 2022
How can I sort an arrayList containing objects without using a sort method from the java collections library?
https://en.wikipedia.org/wiki/Selection_sort#Implementations Translate that to Java. More on reddit.com
🌐 r/learnprogramming
21
2
June 25, 2022
🌐
Coderanch
coderanch.com › t › 452557 › java › Sort-Array-List-Collections-sort
How to Sort an Array List without using Collections.sort() method (Java in General forum at Coderanch)
July 5, 2009 - Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor) ... If you asked them to provide their own sorting algorithm implementation without using Collections.sort or Comparators then they'd fail.
Top answer
1 of 2
7

The roadmap

  • Wikipedia/Sorting algorithm
    • Simple quadratic algorithms
      • Bubble sort - beginner friendly
      • Selection sort - very intuitive
      • Insertion sort - also intuitive
    • Essential comparison-based sort
      • Merge sort - slightly more advanced
      • Quick sort - skip this for now, but watch for it later
    • Essential non-comparison sort
      • Counting sort - important to understand

Your first sorting algorithm

I think counting sort is the best algorithm to start with. Read up about it and try to understand it, then write your own implementation as follows:

  1. Generate 1000 random numbers between 0..9 (use java.util.Random to populate int[])
  2. Sort them using counting sort.

Once you do this, you'll realize how simple sorting can be when you can take advantage of certain properties of the numbers (in this case, the fact that they're between 0..9).

Your second sorting algorithm

Selection sort is a good intuitive sorting algorithm for your next implementation. It's a comparison sort, and doesn't assume anything about the range of the numbers. Many people in real life sort using this algorithm:

  • Given some selection to choose from, we look for the best and pick it first.
  • Now the best is out, so we look for the second best from the rest.
  • Then we look for the third best... etc

The rest of the journey

You may want to implement the other quadratic algorithms just to get a good grasp on the basics, but the next step would be to learn recursion, specifically divide and conquer algorithms.

You would not want to dive straight into merge sort/quick sort without first understanding basic recursion, because it can get too overwhelming.

Do the usual recursion exercises, factorial, Fibonacci, etc. Ask for pointers from stackoverflow if you need guidance. There may even already be questions with good answers about learning recursion.

A side trip

You may want to implement the merge portion of merge sort, even before you fully understand recursion yet. It's a very educational exercise:

  • Given a sorted array of numbers A and a sorted array of numbers B, merge the two into one sorted array
    • Take advantage of the fact that A and B are already sorted
2 of 2
2

Since this is most likely homework I am going to give you advice rather than source code.

Take a look at this page on sorting algorithms. You should choose the correct sorting algorithm based on your requirements. Choosing the wrong algorithm can mean poor performance or unnecessary complexity.

Assuming you have only a small number of items and want a simple algorithm then you could look at insertion sort. The Wikipedia page includes pseudocode. This algorithm has O(n^2) performance.

If your lists are quite long and you want better performance at the cost of a slightly more complicated algorithm, you could try merge sort. This algorithm has O(n log(n)) performance both average and worst case and is a popular choice in language libraries.

Top answer
1 of 3
1

It's hard to get O(1) indexing and O(log n) insertion/deletion in the same data structure. O(1) indexing means we can't afford the link-following involved in indexing a tree, list, skip list, or other link-based data structure, while O(log n) modification means we can't afford to shift half the elements of an array on every insertion. I don't know if it's possible to fulfill these requirements simultaneously.

If we relax one of these requirements, things become much easier. For example, O(log n) for all operations can be achieved by an indexable skip list or a self-balancing BST with nodes that keep track of the size of the subtree rooted at the node. Neither of these can be built on top of the skip list or BST in Java's standard library, though, so you'd probably need to install another library or write your own data structure.

O(1) indexing, O(log n) search, and O(n) insert and delete can be done by keeping a sorted ArrayList and using Collections.binarySearch to search for elements or insert/delete positions. You never need to call Collections.sort, but you still need to call the ArrayList's O(n) insert and delete methods. This is probably the easiest option to build on top of Java's built-in tools. Note that with recent Java versions, Collections.sort is an adaptive mergesort that would take O(n) time to sort an array where only the last element is out of sorted order, so you could probably get away with relying on Collections.sort. However, that's an implementation detail that alternative Java implementations don't have to follow.

2 of 3
1

If your primary goal is O(1) for indexed lookup (get()), then you can implement your own class implementing List, backed by an array, using Arrays.binarySearch().

retrieve: get(int)         - O(1)     - array index
search:   contains(Object) - O(log n) - binarySearch
          indexOf(Object)  - O(log n) - binarySearch
insert:   add(E)           - O(n)     - binarySearch + array shift
delete:   remove(int)      - O(n)     - array shift
          remove(Object)   - O(n)     - binarySearch + array shift

The add(E) method is violating the List definition (append), but is consistent with the Collection definition.

The following methods should throw UnsupportedOperationException:

add(int index, E element)
addAll(int index, Collection<? extends E> c)
set(int index, E element)

If duplicate values are not allowed, which could be a logical restriction, consider also implementing NavigableSet, which is a SortedSet.

🌐
W3Schools
w3schools.com › java › java_sort_list.asp
Java Sort a List - List Sorting
Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically.
🌐
Quora
quora.com › How-do-I-sort-an-arraylist-without-using-collections-sort
How to sort an arraylist without using collections.sort - Quora
Answer (1 of 5): Depends on the datatype your Arraylist is holding. For numbers you can write a program that'll take the Arraylist as parameter and sort it and so on for other datatypes.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-sort-list
How to Sort a List in Java | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-sort-a-list-in-java
How to Sort a List in Java – Java List Sorting Example
January 24, 2023 - We call this process sorting. Sorting refers to arranging data in a specific order using certain criteria. You can sort different types of data, including numbers, strings, and objects. Java provides built-in methods for sorting, such as the Collections classes.
🌐
Reddit
reddit.com › r/learnjava › sorting array list without using .sort in java
r/learnjava on Reddit: Sorting array list without using .sort in Java
October 2, 2022 -

Hi so I made this method that should sort items by weight (descending order), but the tests aren't working can someone pls help? The first two assertEquals work but at the 3rd one the output my code gives is 2 but it should be 0 :

Expected :0

Actual :2

here's the assignment description:

Task 7: Item Storage

Your program should have an Item Bag to store items. An item bag has a maximum weight defined when creating the bag. The bag also stores a collection of items that begins empty when creating the bag. The maximum weight cannot change once the bag is created. You don’t need to write code to check if two bags are equal.

The bag should provide: the current number of items stored, the current weight of the bag, and its maximum weight. Other operations are defined below.

7.1 - Adding items to the bag:

The collection of items can accept repeated items and the items are stored in a specific sequence. When adding an item to the bag, the item must be placed in the index where its weight is higher than the items after them and lighter than those before (i.e., sorted by weight).

When adding an item to the bag, the method should return the index in which the item was added. If the bag cannot fit the item (it goes above the max weight), you should return -1.

Note: You don’t need to use Arrays.sort or Collections.sort for solving this task. In fact, using these sorting libraries can make your code inefficient.

public int addItem(Item item1) {                            
                                                            
    bagOfItems.add(item1);                                  
                                                            
    int index = 0;                                          
                                                            
    for (Item item : bagOfItems) {                          
                                                            
        if (item.weight < item1.weight) {                   
            bagOfItems.set(bagOfItems.indexOf(item), item1);
            bagOfItems.set(bagOfItems.indexOf(item1), item);
                                                            
            index = bagOfItems.indexOf(item1);              
        } else if (this.currentWeight >= this.maxWeight) {            
             index = -1;                                    
        }                                                   
    }           return index;                               
}                  

here's the test class:



    @Test
    public void shouldAddItemsCorrectly() {
        Item potion1 = new Item("Potion", 20, 5.0);
        Item potion2 = new Item("Potion", 20, 5.0);
        Item potion3 = new Item("Potion", 20, 5.0);

        Item hyperPotion = new Item("Hyper Potion", 50, 10.0);
        Item superPotion = new Item("Super Potion", 40, 8.3);

        ItemBag itemBag = new ItemBag(30.0);
        assertEquals(0, itemBag.addItem(potion1));
        assertEquals(0, itemBag.addItem(potion2));
         assertEquals(0, itemBag.addItem(hyperPotion)); //the problem is here
        assertEquals(1, itemBag.addItem(superPotion));
        assertEquals(-1, itemBag.addItem(potion3));

        assertEquals(4, itemBag.getNumOfItems());
        assertEquals(28.3, itemBag.getCurrentWeight());
    }
}
Top answer
1 of 2
3
Note: You don’t need to use Arrays.sort or Collections.sort for solving this task. In fact, using these sorting libraries can make your code inefficient. What this is suggesting is that you don't need to sort the whole list (using a premade or your own sorting algorithm) at any point. Instead, you maintain the list in decreasing order all the time. So always when adding items to the bag, you iterate the existing items and insert the new item in the correct position according to the wanted order.
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Medium
medium.com › @samrat.alam › default-library-sorting-in-java-list-set-and-map-42e9f172d86b
Default Library Sorting in Java: List, Set, and Map | by Samrat Alam | Medium
November 28, 2025 - Default Library Sorting in Java: List, Set, and Map Sorting is one of the most common operations in programming. In Java, the standard library provides powerful, easy-to-use methods to sort …
🌐
Reddit
reddit.com › r/learnprogramming › how can i sort an arraylist containing objects without using a sort method from the java collections library?
r/learnprogramming on Reddit: How can I sort an arrayList containing objects without using a sort method from the java collections library?
June 25, 2022 -

I have this code I am working on for a homework assignment, but the professor has specified that we cannot use anything from java collections. The issue is that all of his examples use collections, and all of his examples about sorting only cover sorting an int array. The code I am writing has to sort the array by both "rollno"(the int variable assigned to each "student" object) and by "name"(the string variable assigned to each "student").

The assignment calls for the use of a selection sort method, so I want to sort the numbers in order from 1-10 and sort the names by string length. If anyone can guide me forward on this I would greatly appreciate it because I am lost on how to even begin a selection sort method.

Sidenote: The github has four files in it; "arrSort", "Student", "rollComp", and "nameComp". "arrSort" is the main method and is where I am trying to implement the sort method, "Student" is the object class, "rollComp" and "nameComp" are both comparator classes. All of these files are copied directly from my IDE, and if you notice ANY errors in how I have formatted anything, or if you have any other questions please let me know.

🌐
Reddit
reddit.com › r/learnprogramming › sorting array list without using .sort in java
r/learnprogramming on Reddit: Sorting array list without using .sort in Java
October 2, 2022 -

Hi so I made this method that should sort items by weight (descending order), but the tests aren't working can someone pls help? The first two assertEquals work but at the 3rd one the output my code gives is 2 but it should be 0 :

Expected :0

Actual :2

here's the assignment description:

Task 7: Item Storage

Your program should have an Item Bag to store items. An item bag has a maximum weight defined when creating the bag. The bag also stores a collection of items that begins empty when creating the bag. The maximum weight cannot change once the bag is created. You don’t need to write code to check if two bags are equal.

The bag should provide: the current number of items stored, the current weight of the bag, and its maximum weight. Other operations are defined below.

7.1 - Adding items to the bag:

The collection of items can accept repeated items and the items are stored in a specific sequence. When adding an item to the bag, the item must be placed in the index where its weight is higher than the items after them and lighter than those before (i.e., sorted by weight).

When adding an item to the bag, the method should return the index in which the item was added. If the bag cannot fit the item (it goes above the max weight), you should return -1.

Note: You don’t need to use Arrays.sort or Collections.sort for solving this task. In fact, using these sorting libraries can make your code inefficient.

public int addItem(Item item1) {                            
                                                            
    bagOfItems.add(item1);                                  
                                                            
    int index = 0;                                          
                                                            
    for (Item item : bagOfItems) {                          
                                                            
        if (item.weight < item1.weight) {                   
            bagOfItems.set(bagOfItems.indexOf(item), item1);
            bagOfItems.set(bagOfItems.indexOf(item1), item);
                                                            
            index = bagOfItems.indexOf(item1);              
        } else if (this.currentWeight >= this.maxWeight) {            
             index = -1;                                    
        }                                                   
    }           return index;                               
}                  

here's the test class:



    @Test
    public void shouldAddItemsCorrectly() {
        Item potion1 = new Item("Potion", 20, 5.0);
        Item potion2 = new Item("Potion", 20, 5.0);
        Item potion3 = new Item("Potion", 20, 5.0);

        Item hyperPotion = new Item("Hyper Potion", 50, 10.0);
        Item superPotion = new Item("Super Potion", 40, 8.3);

        ItemBag itemBag = new ItemBag(30.0);
        assertEquals(0, itemBag.addItem(potion1));
        assertEquals(0, itemBag.addItem(potion2));
         assertEquals(0, itemBag.addItem(hyperPotion)); //the problem is here
        assertEquals(1, itemBag.addItem(superPotion));
        assertEquals(-1, itemBag.addItem(potion3));

        assertEquals(4, itemBag.getNumOfItems());
        assertEquals(28.3, itemBag.getCurrentWeight());
    }
}
Top answer
1 of 2
4
Okay. Why does it do that? You have the code in front of you. You can trace it through, line by line. What happens at each step? What does the bag look like before you add the item? Where should the item go? If you know how to use a debugger, do so. If you don't know how to use a debugger then start adding println statements to the code so that you know exactly what is going on. print out everything you can think of. Your code is doing things in an odd way, IMHO. I would normally expect that you'd skip over the items with a weight of less than the new item and then, when you find an item that is heavier than yours, "move up" everything after that to make space for yours. You start off by putting your item in the very first position, which seems very wrong to me. Your next question is probably going to be "How do I fix this code?". TBH, I don't think you "fix" this so much as rewrite it from scratch. Write down a clear set of instructions, stating what the function will do. Super detailed. Then implement that.
2 of 2
4
The problem is poorly stated. You have two weights associated with ItemBag: currentWeight and maximumWeight. The Item itself seems to be a name, the number of items, and weight. Let's think about what happens. You add potion1 to an empty list. Since there's only one item in the list, then that item can't be less than itself. You add potion2 to the list (which is added at the end). It has the same weight as potion 1. So both items in the list are 5.0. So again, the if-condition is not true, so nothing happens. The default value of index is 0. so it returns 0. You add hyperpotion which has a weight of 15.0. So you list looks like [5.0, 5.0, 15.0]. The result is supposed to be in descending order (values grow smaller). Currently, it's in ascending order. Go through the code, in particular, the if statement. How many times is it true or false? Just before the if statement and underneath the for statement in addItem, do the following System.out.println("item.weight = " + item.weight + "item1.weight = " + item1.weight); System.out.println("item.weight < item1.weight: " + (item.weight < item1.weight) This will show you what values item and item1 have and whether the condition checked for in the if-condition is true or false. Also, you never update currentWeight. Print the currentWeight after the else statement in addItem, and I think you'll see it's always 0. There are other errors, but these are the most immediate ones.
🌐
Reddit
reddit.com › r/javahelp › question regarding sorting lists without collections
r/javahelp on Reddit: Question regarding sorting lists without collections
December 9, 2022 -

Hey, this week I was introduced and working with lists and one task is to sort a list without using collections. The problem isn’t that I don’t know how to do it but rather that I think that my first intuition doesn’t seem like a good approach.

The first thing that came to my mind would be to loop over the list to count the length, then create a new array and then loop again over the list to copy the values into the array. Then I would insertionSort the array and then create a new list and lastly change the head to point at the new list.

All in all, I’m pretty sure this should work and shouldn’t be too hard but it seems like too many extra steps and thus creating ugly code.

So do you have any other solutions how I could approach that problem?

🌐
YouTube
youtube.com › daniel sutantyo
CP-1.010 Java Tutorial - Sorting an ArrayList - YouTube
Problem: Sort of Sorting (https://open.kattis.com/problems/sortofsorting)In this video I discuss how you can sort an ArrayList. In case you haven't used an A...
Published: September 14, 2021
Views: 3K
🌐
GeeksforGeeks
geeksforgeeks.org › java › sorting-in-java
Sorting in Java - GeeksforGeeks
Sorting in Java is used to arrange elements in a specific order (ascending or descending).
Published: April 16, 2026
🌐
W3Schools
w3schools.com › java › ref_arraylist_sort.asp
Java ArrayList sort() Method
The sort() method sorts items in the list. A Comparator can be used to compare pairs of elements.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-collections-sort
Java Collections sort() | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.