5

I have an array I want to check the the last digits if it is in the array.

Example:

String[] types = {".png",".jpg",".gif"}

String image = "beauty.jpg";
// Note that this is wrong. The parameter required is a string not an array.
Boolean true = image.endswith(types); 

Please note: I know I can check each individual item using a for loop.

I want to know if there is a more efficient way of doing this. Reason being is that image string is already on a loop on a constant change.

3
  • 1
    Are you really attempting to name a boolean "true"? Or is that for some demonstration purposes? Commented Jun 19, 2012 at 18:06
  • 1
    @GearsdfGearsdfas true is a reserved keyword by Java. And it's just not a very good variable name anyway- not very descriptive. Commented Jun 19, 2012 at 18:12
  • oh LOL i wasn't thinking of using true it just happened. @DavidB Commented Jun 19, 2012 at 18:20

3 Answers 3

14
Arrays.asList(types).contains(image.substring(image.lastIndexOf('.') + 1))
Sign up to request clarification or add additional context in comments.

1 Comment

Even simpler than mine. :) Does asList actually convert the array to a list every time?
5

You can substring the last 4 characters:

String ext = image.substring(image.length - 4, image.length);

and then use a HashMap or some other search implementation to see if it is in your list of approved file extensions.

if(fileExtensionMap.containsKey(ext)) {

Comments

0

Use Arrays.asList to convert to a List. Then you can check for membership.

String[] types = {".png",".jpg",".gif"};
String image = "beauty.jpg";
if (image.contains(".")) 
    System.out.println(Arrays.asList(types).contains(
        image.substring(image.lastIndexOf('.'), image.length())));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.