Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

[Java] Reverse Char Array?

array char array reverse array

  • Please log in to reply
11 replies to this topic

#1 900900

900900

    CC Newcomer

  • Member
  • PipPip
  • 10 posts
  • Learning:Java, C#, PHP, Lua

Posted 24 June 2012 - 02:30 PM

More trouble I can't seem to find anything on. Reversing a CHAR array in Java.

As you can see I created a new CHAR array with 5 characters. I am trying to create a method that will will reverse the CHAR array and spit it out back at the user.

So my method needs to contain the code to reverse the CHAR array. I have absolutely 0 clue what to do to create some code that will reverse a char array. Is there some sort of class I can use? (charArray.REVERSE ? something like that) or do I have to write some sort of loop to do this?

public class Reverse {
public static  void main(String[] args) {

  char[] charArray = { 'b', 'o', 'b', 'b', 'y' };

  reverseIT(charArray);

  System.out.println(charArray);

  }
private static  int[] reverseIT(char[] list) {
  char result = int[0];

  //Reverse CHAR ARRAY

  return result;

}


  • 0

#2 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 24 June 2012 - 03:58 PM

char result = int[0];

This line in your reverseIt function doesn't work since result is a char but you are initiializing it as an array. Also, why create an array of size 0?

To reverse a list you can either:

(1) Make a new array and loop backwards creating a new array:

int idx = 0;
char[] newArr = new char[A.length];
for (int i = A.length - 1; i >= 0; i--) {
   newArr[idx] = A[i];
   idx++;
}

The other option, which is much faster and uses 0(1) memory is to do the swap in place. Basically you start at the far right and swap with the first element. Then move a pointer at the end closer to the front and a point at the front closer to the end and do another swap. Once the two pointers swap (which will happen halfway through the list) you stop. This means that you only need to iterate over half of the array and you don't need a second array.

public static void reverseIT(char[] A) {
		int idx = 0;
		for (int i = A.length - 1; i >= A.length / 2; i--) {

			char temp = A[i];
			A[i] = A[idx];
			A[idx] = temp;
			idx++;
		}
	}

  • 1

#3 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 25 June 2012 - 06:53 AM

Shortest code using java API.
You may want to use more than 1 line though :P

char[] charArray = { 'b', 'o', 'b', 'b', 'y' };
char[] reversed = new StringBuilder(new String(charArray)).reverse().toString().toCharArray();

  • 0

#4 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 25 June 2012 - 07:20 AM

Mine is more efficient than that... yours creates several new object instances.
  • 0

#5 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 26 June 2012 - 03:53 AM

True, but there's such thing as "Premature optimization is the root of all evil", and "Don't optimize too early".
And really, it's just a main doing 1 reverse thingy. If I do 10 million 'bobby' reversals, it takes 900-1100ms, which is ~0,0001ms per reversal.
Still, yours is about factor 10 faster.

It's often a trade between readability and performance.
  • 1

#6 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts
  • Location:Argentina
  • Programming Language:C, C++, C#, PHP, JavaScript, Transact-SQL, Bash, Others
  • Learning:Java, Others

Posted 26 June 2012 - 06:20 AM

I like what wim is saying, i think it is a very polemic matter in between coders, no doubt that programing is about efficiency, so, chili has a big point there, thing is the line we draw in between programs that has no performance needs and the one who really does,
lets face, most of systems are not Production's, are not online and not real time.

so, sometimes you need to put the efficiency in the computing, by excel coding, and some other times you need efficiency on the "easy code" writing, particularly on those code pieces that will be upgraded, as any reporting or administrative program, that is my point of view, of course if you are doing a real time system, you even rewrite C's strcpy function performance base, in a similar way that chilli's reverse.

what do you think guys ? how often do you confront with this dilemma ? easy reading code or performance code ?
  • 0

#7 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 26 June 2012 - 06:49 AM

Whether I would write this code with loops like chili5 or not would depend entirely on how often that part is used. And how big the impact would be.

You can use profiling software to profile your running code, and it will show which parts of your code it spents most time at.
And those are the parts you should focus on IF you desire better performance.

For example a 200 line method (is bad, you should split it up), may be called once per day on a running server. Even if it's kinda slow, its impact is minimal.
If a 5 liner, however, is called 100 times per minute. Then that is something more interesting looking at.
(Even short methods, at first sight not improvable, may possibly get improved with caching)
  • 0

#8 jjwooyoung

jjwooyoung

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 04 June 2015 - 09:47 PM

Sorry for old thread revival, but I recently saw a way of reversing that I didn't think of. It was something like this:

public char reverseString(char[] str) {
    int length = str.length();
 
    char temp[length];
 
    for(int i = 0; i < str.length; i++) {
        temp[i] = str[length - i - 1];
    }
    ...
}

I usually just do the swaping as mentioned above. But you think this way is better?


Edited by jjwooyoung, 04 June 2015 - 09:48 PM.

  • 0

#9 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 05 June 2015 - 12:00 AM

The main difference between the way you posted and above is that the one you posted does not change the original array. So if you want to reverse the array, but also still want to have the original array for later use. Your way would be much better.

The downside of your code is that you will create 2 arrays of characters, doubling the memory use required for the string reversing.

 

I would probably use the way above from chili5 myself assuming I don't need the original array.

Though reversing an array is something you rarely do in normal life code situations :)


  • 0

#10 AlvinFang

AlvinFang

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 10 July 2016 - 08:37 PM

public static void reverseIT(char[] A) {
        int idx = 0;
        for (int i = A.length - 1; i >= A.length / 2; i--) {

            char temp = A[i];
            A[i] = A[idx];
            A[idx] = temp;
            idx++;
        }
    }

 

This solution by chilli5 seems interesting... but because Java is pass by value, doesn't changing A[] directly do nothing to the original char array values? 

 

Or is it an exception for arrays cause they reference an address, and you can change original values that way?

 


  • 0

#11 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 12 July 2016 - 10:57 PM

Anything which is not a primitive (int, boolean, double, ...), eg. Which is a class instance, will behave that way.
Array objects are actually instances of the Array class in Java so they will behave exactly like any other class instance.
 
Whenever an instance of a class is passed as parameter, the instance itself can be modified, and it will modify the source's instance. However the variable can't be reassigned, so it's not strictly pass-by-reference.
 

class Address {
  private String street;
  private String postcode;

  // getter and setter
}

class Test {
  public static void main(String... args) {
    Address address = Address();
    fillAddress(address)
    System.out.println("1: " + address.getStreet() + " " + address.getPostcode());
    setAddress(address)
    System.out.println("2: " + address.getStreet() + " " + address.getPostcode());
  }
  
  public static void fillAddress(Address address) {
    address.setStreet("A");
    address.setPostcode("B");
  }

  public static void setAddress(Address address) {
    address = Address();
    address.setStreet("C");
    address.setPostcode("D");
  }
}

The output of this will be:

1: A B
2: A B

Because in the setAddress() method you set "C" and "D" to a new object. But since the variables themselves are not pass by reference, the new object is lost.

In fillAddress() the parameter variable actually contains the object by reference of the original address.


  • 0

#12 Randallltus

Randallltus

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 04 January 2017 - 04:57 AM

I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ? Since arrays keep all the data in a contiguous chunk of memory unlike Lists, would the use of an array to store thousands of strings cause problems ?
  • 0





Also tagged with one or more of these keywords: array, char array, reverse array