Comparing Array sizes of different types in java [duplicate]












7
















This question already has an answer here:




  • How can I make a method take an array of any type as a parameter?

    4 answers




So I want to create a method that validates that two Arrays are of same length like:



validateSameSize(Object first, Object second) {
if (first.length != second.length) throw new Exception();
}


The problem is that this method only works for non-primitive Arrays. If I want to compare a char-Array with another array this does not work. Is there a way to implement this function without too much overhead?



I have already tried



<T,V> validateSameSize(T first, V second)


but since generics also need a class and don't work with primitive types, this does not work. Also



validateSameSize(Array first, Array second)


doesn't work either










share|improve this question













marked as duplicate by Sotirios Delimanolis java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Jan 26 at 20:29


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.























    7
















    This question already has an answer here:




    • How can I make a method take an array of any type as a parameter?

      4 answers




    So I want to create a method that validates that two Arrays are of same length like:



    validateSameSize(Object first, Object second) {
    if (first.length != second.length) throw new Exception();
    }


    The problem is that this method only works for non-primitive Arrays. If I want to compare a char-Array with another array this does not work. Is there a way to implement this function without too much overhead?



    I have already tried



    <T,V> validateSameSize(T first, V second)


    but since generics also need a class and don't work with primitive types, this does not work. Also



    validateSameSize(Array first, Array second)


    doesn't work either










    share|improve this question













    marked as duplicate by Sotirios Delimanolis java
    Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

    StackExchange.ready(function() {
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function() {
    $hover.showInfoMessage('', {
    messageElement: $msg.clone().show(),
    transient: false,
    position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
    dismissable: false,
    relativeToBody: true
    });
    },
    function() {
    StackExchange.helpers.removeMessages();
    }
    );
    });
    });
    Jan 26 at 20:29


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





















      7












      7








      7


      0







      This question already has an answer here:




      • How can I make a method take an array of any type as a parameter?

        4 answers




      So I want to create a method that validates that two Arrays are of same length like:



      validateSameSize(Object first, Object second) {
      if (first.length != second.length) throw new Exception();
      }


      The problem is that this method only works for non-primitive Arrays. If I want to compare a char-Array with another array this does not work. Is there a way to implement this function without too much overhead?



      I have already tried



      <T,V> validateSameSize(T first, V second)


      but since generics also need a class and don't work with primitive types, this does not work. Also



      validateSameSize(Array first, Array second)


      doesn't work either










      share|improve this question















      This question already has an answer here:




      • How can I make a method take an array of any type as a parameter?

        4 answers




      So I want to create a method that validates that two Arrays are of same length like:



      validateSameSize(Object first, Object second) {
      if (first.length != second.length) throw new Exception();
      }


      The problem is that this method only works for non-primitive Arrays. If I want to compare a char-Array with another array this does not work. Is there a way to implement this function without too much overhead?



      I have already tried



      <T,V> validateSameSize(T first, V second)


      but since generics also need a class and don't work with primitive types, this does not work. Also



      validateSameSize(Array first, Array second)


      doesn't work either





      This question already has an answer here:




      • How can I make a method take an array of any type as a parameter?

        4 answers








      java arrays






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 26 at 18:34









      SchottkySchottky

      362




      362




      marked as duplicate by Sotirios Delimanolis java
      Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Jan 26 at 20:29


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









      marked as duplicate by Sotirios Delimanolis java
      Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Jan 26 at 20:29


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


























          2 Answers
          2






          active

          oldest

          votes


















          9














          You can use Array#getLength:



          public static boolean sameSize(Object arrayA, Object arrayB) {
          return Array.getLength(arrayA) == Array.getLength(arrayB);
          }


          It will work with non-primitive arrays as well as with primitive ones:



          System.out.println(sameSize(new int[0], new int[100])); // false
          System.out.println(sameSize(new char[0], new int[0])); // true
          System.out.println(sameSize(new Object[0], new Object[0])); // true
          System.out.println(sameSize(new Object[0], new List[0])); // true




          Also don't forget that passing an Object that is not an array to Array#getLength will result in IllegalArgumentException.



          This code:



          Object notArray = 100;
          System.out.println(Array.getLength(notArray));


          produces:



          Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array




          If you need to fail fast before invoking Array#getLength you can check if the argument is actually array:



          if (!object.getClass().isArray()) {
          // object is not array. Do something with it
          }





          share|improve this answer


























          • Thank you so much! So just for clarification: a primitive Array does not inherit from Object, but a primitive value does inherit from Object?

            – Schottky
            Jan 26 at 18:45











          • No, primitive types do not take part in inheritance at all. An int is not an object, it is just the number. The Java Language Specification probably has a chapter called Primitive Types, which would be the definitive source on this topic.

            – Roland Illig
            Jan 26 at 18:51













          • @Schottky Every Java array is an Object, whether its elements are Objects or not.

            – Boann
            Jan 27 at 17:13



















          3














          The caco3 answer is fine.

          Note that if the Object params are not arrays you will discover it only at runtime.

          A safer way would be to overload the method for primitives :



          void validateSameSize(Object first, Object second) throws Exception {
          if (first.length != second.length) throw new Exception();
          }

          void validateSameSize(int first, int second) throws Exception {
          if (first.length != second.length) throw new Exception();
          }


          And so for...

          It will require you to write more code but your code would be more robust.






          share|improve this answer






























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            9














            You can use Array#getLength:



            public static boolean sameSize(Object arrayA, Object arrayB) {
            return Array.getLength(arrayA) == Array.getLength(arrayB);
            }


            It will work with non-primitive arrays as well as with primitive ones:



            System.out.println(sameSize(new int[0], new int[100])); // false
            System.out.println(sameSize(new char[0], new int[0])); // true
            System.out.println(sameSize(new Object[0], new Object[0])); // true
            System.out.println(sameSize(new Object[0], new List[0])); // true




            Also don't forget that passing an Object that is not an array to Array#getLength will result in IllegalArgumentException.



            This code:



            Object notArray = 100;
            System.out.println(Array.getLength(notArray));


            produces:



            Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array




            If you need to fail fast before invoking Array#getLength you can check if the argument is actually array:



            if (!object.getClass().isArray()) {
            // object is not array. Do something with it
            }





            share|improve this answer


























            • Thank you so much! So just for clarification: a primitive Array does not inherit from Object, but a primitive value does inherit from Object?

              – Schottky
              Jan 26 at 18:45











            • No, primitive types do not take part in inheritance at all. An int is not an object, it is just the number. The Java Language Specification probably has a chapter called Primitive Types, which would be the definitive source on this topic.

              – Roland Illig
              Jan 26 at 18:51













            • @Schottky Every Java array is an Object, whether its elements are Objects or not.

              – Boann
              Jan 27 at 17:13
















            9














            You can use Array#getLength:



            public static boolean sameSize(Object arrayA, Object arrayB) {
            return Array.getLength(arrayA) == Array.getLength(arrayB);
            }


            It will work with non-primitive arrays as well as with primitive ones:



            System.out.println(sameSize(new int[0], new int[100])); // false
            System.out.println(sameSize(new char[0], new int[0])); // true
            System.out.println(sameSize(new Object[0], new Object[0])); // true
            System.out.println(sameSize(new Object[0], new List[0])); // true




            Also don't forget that passing an Object that is not an array to Array#getLength will result in IllegalArgumentException.



            This code:



            Object notArray = 100;
            System.out.println(Array.getLength(notArray));


            produces:



            Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array




            If you need to fail fast before invoking Array#getLength you can check if the argument is actually array:



            if (!object.getClass().isArray()) {
            // object is not array. Do something with it
            }





            share|improve this answer


























            • Thank you so much! So just for clarification: a primitive Array does not inherit from Object, but a primitive value does inherit from Object?

              – Schottky
              Jan 26 at 18:45











            • No, primitive types do not take part in inheritance at all. An int is not an object, it is just the number. The Java Language Specification probably has a chapter called Primitive Types, which would be the definitive source on this topic.

              – Roland Illig
              Jan 26 at 18:51













            • @Schottky Every Java array is an Object, whether its elements are Objects or not.

              – Boann
              Jan 27 at 17:13














            9












            9








            9







            You can use Array#getLength:



            public static boolean sameSize(Object arrayA, Object arrayB) {
            return Array.getLength(arrayA) == Array.getLength(arrayB);
            }


            It will work with non-primitive arrays as well as with primitive ones:



            System.out.println(sameSize(new int[0], new int[100])); // false
            System.out.println(sameSize(new char[0], new int[0])); // true
            System.out.println(sameSize(new Object[0], new Object[0])); // true
            System.out.println(sameSize(new Object[0], new List[0])); // true




            Also don't forget that passing an Object that is not an array to Array#getLength will result in IllegalArgumentException.



            This code:



            Object notArray = 100;
            System.out.println(Array.getLength(notArray));


            produces:



            Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array




            If you need to fail fast before invoking Array#getLength you can check if the argument is actually array:



            if (!object.getClass().isArray()) {
            // object is not array. Do something with it
            }





            share|improve this answer















            You can use Array#getLength:



            public static boolean sameSize(Object arrayA, Object arrayB) {
            return Array.getLength(arrayA) == Array.getLength(arrayB);
            }


            It will work with non-primitive arrays as well as with primitive ones:



            System.out.println(sameSize(new int[0], new int[100])); // false
            System.out.println(sameSize(new char[0], new int[0])); // true
            System.out.println(sameSize(new Object[0], new Object[0])); // true
            System.out.println(sameSize(new Object[0], new List[0])); // true




            Also don't forget that passing an Object that is not an array to Array#getLength will result in IllegalArgumentException.



            This code:



            Object notArray = 100;
            System.out.println(Array.getLength(notArray));


            produces:



            Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array




            If you need to fail fast before invoking Array#getLength you can check if the argument is actually array:



            if (!object.getClass().isArray()) {
            // object is not array. Do something with it
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 26 at 19:10

























            answered Jan 26 at 18:40









            caco3caco3

            1,9181720




            1,9181720













            • Thank you so much! So just for clarification: a primitive Array does not inherit from Object, but a primitive value does inherit from Object?

              – Schottky
              Jan 26 at 18:45











            • No, primitive types do not take part in inheritance at all. An int is not an object, it is just the number. The Java Language Specification probably has a chapter called Primitive Types, which would be the definitive source on this topic.

              – Roland Illig
              Jan 26 at 18:51













            • @Schottky Every Java array is an Object, whether its elements are Objects or not.

              – Boann
              Jan 27 at 17:13



















            • Thank you so much! So just for clarification: a primitive Array does not inherit from Object, but a primitive value does inherit from Object?

              – Schottky
              Jan 26 at 18:45











            • No, primitive types do not take part in inheritance at all. An int is not an object, it is just the number. The Java Language Specification probably has a chapter called Primitive Types, which would be the definitive source on this topic.

              – Roland Illig
              Jan 26 at 18:51













            • @Schottky Every Java array is an Object, whether its elements are Objects or not.

              – Boann
              Jan 27 at 17:13

















            Thank you so much! So just for clarification: a primitive Array does not inherit from Object, but a primitive value does inherit from Object?

            – Schottky
            Jan 26 at 18:45





            Thank you so much! So just for clarification: a primitive Array does not inherit from Object, but a primitive value does inherit from Object?

            – Schottky
            Jan 26 at 18:45













            No, primitive types do not take part in inheritance at all. An int is not an object, it is just the number. The Java Language Specification probably has a chapter called Primitive Types, which would be the definitive source on this topic.

            – Roland Illig
            Jan 26 at 18:51







            No, primitive types do not take part in inheritance at all. An int is not an object, it is just the number. The Java Language Specification probably has a chapter called Primitive Types, which would be the definitive source on this topic.

            – Roland Illig
            Jan 26 at 18:51















            @Schottky Every Java array is an Object, whether its elements are Objects or not.

            – Boann
            Jan 27 at 17:13





            @Schottky Every Java array is an Object, whether its elements are Objects or not.

            – Boann
            Jan 27 at 17:13













            3














            The caco3 answer is fine.

            Note that if the Object params are not arrays you will discover it only at runtime.

            A safer way would be to overload the method for primitives :



            void validateSameSize(Object first, Object second) throws Exception {
            if (first.length != second.length) throw new Exception();
            }

            void validateSameSize(int first, int second) throws Exception {
            if (first.length != second.length) throw new Exception();
            }


            And so for...

            It will require you to write more code but your code would be more robust.






            share|improve this answer




























              3














              The caco3 answer is fine.

              Note that if the Object params are not arrays you will discover it only at runtime.

              A safer way would be to overload the method for primitives :



              void validateSameSize(Object first, Object second) throws Exception {
              if (first.length != second.length) throw new Exception();
              }

              void validateSameSize(int first, int second) throws Exception {
              if (first.length != second.length) throw new Exception();
              }


              And so for...

              It will require you to write more code but your code would be more robust.






              share|improve this answer


























                3












                3








                3







                The caco3 answer is fine.

                Note that if the Object params are not arrays you will discover it only at runtime.

                A safer way would be to overload the method for primitives :



                void validateSameSize(Object first, Object second) throws Exception {
                if (first.length != second.length) throw new Exception();
                }

                void validateSameSize(int first, int second) throws Exception {
                if (first.length != second.length) throw new Exception();
                }


                And so for...

                It will require you to write more code but your code would be more robust.






                share|improve this answer













                The caco3 answer is fine.

                Note that if the Object params are not arrays you will discover it only at runtime.

                A safer way would be to overload the method for primitives :



                void validateSameSize(Object first, Object second) throws Exception {
                if (first.length != second.length) throw new Exception();
                }

                void validateSameSize(int first, int second) throws Exception {
                if (first.length != second.length) throw new Exception();
                }


                And so for...

                It will require you to write more code but your code would be more robust.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 26 at 19:01









                davidxxxdavidxxx

                68.7k67399




                68.7k67399















                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith