Results 1 to 4 of 4
- 04-24-2011, 01:57 PM #1
Member
- Join Date
- Apr 2010
- Posts
- 2
- Rep Power
- 0
Delete Middle element from arrray
Hi
I want delete one of the middle element in an aray
how can i do this;
I have tried like this ;
Say;
I want to remove "3" from arr
after removing this output should be like this;
Current ---> "1","2","3","4","5","6"
Expecting ---> "1","2","4","5","6","" (should shift elements by 1 after deleting )
Java Code:String arr[] = {"1","2","3","4","5","6"}; for (int i = 0; i < arr.length; i++) { if (arr[i] == "3") { String temp[] = new String[arr.length]; for (int j = 0; j < i; j++) { temp[j] = arr[j]; } for (int k = i; (k > i) && (k < arr.length); k++) { temp[k-1] = arr[k]; } arr = temp; } } for (int j = 0; j < arr.length; j++) { System.out.println(arr[j]); }
How can i perform this
Pl help
- 04-24-2011, 02:09 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Why do not use a list? :confused:
Or create a new smaller array and iterate over the other one and set all elements except the "3"(index two)Java Code:String arr[] = { "1","2","3","4","5","6" }; List<String> list = new ArrayList<String>( Arrays.asList(arr)); list.remove("3"); arr = list.toArray(new String[]{});
- 04-24-2011, 07:15 PM #3
Senior Member
- Join Date
- Aug 2010
- Posts
- 127
- Rep Power
- 0
What does "{}" do here? Without it, my compiler asks for a dimension, but with it, there is no error. Why?Java Code:String arr[] = { "1","2","3","4","5","6" }; List<String> list = new ArrayList<String>( Arrays.asList(arr)); list.remove("3"); arr = list.toArray(new String[][U][COLOR="Red"]{}[/COLOR][/U]);
- 04-24-2011, 07:25 PM #4
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Why? Read http://java.sun.com/docs/books/jls/t...ml/arrays.html
--> An array is created by an array creation expression (§15.10) or an array initializer (§10.6).
You can also write
arr = list.toArray(new String[0]);
:D
Similar Threads
-
how to set my frame in the middle of the screen
By Alexis in forum AWT / SwingReplies: 4Last Post: 11-21-2010, 10:23 AM -
Trying to make an array list // inserting an element to middle of array
By javanew in forum New To JavaReplies: 2Last Post: 09-06-2010, 01:03 AM -
JPanel Array with Color arrray
By Chanel in forum New To JavaReplies: 10Last Post: 07-31-2010, 02:18 PM -
Find the Middle of a JFrame??
By bdizzle in forum AWT / SwingReplies: 9Last Post: 02-21-2010, 08:39 PM -
How to delete a JLabel by using the keyboard 'delete' key?
By Suren in forum AWT / SwingReplies: 2Last Post: 04-20-2009, 08:00 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks