سؤال

وأي شخص يعرف كيفية كتابة قطعة من التعليمات البرمجية أدناه باستخدام الأدوية وتجنب تحذيرات المترجم؟ (SuppressWarnings ( "دون رادع") يعتبر الغش).

و، ربما، والتحقق عن طريق الوراثة أن هذا النوع من "اليسار" هو نفسه كنوع من "الحق"؟

public void assertLessOrEqual(Comparable left, Comparable right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}
هل كانت مفيدة؟

المحلول

وهذا يعمل مع الفئات الفرعية من أنواع المقارنة أيضا:

public <T extends Comparable<? super T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || left.compareTo(right) > 0) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}

نصائح أخرى

وماذا عن هذا:

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || (left.compareTo(right) > 0)) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}

وربما يمكن أن يكون وو<م> قليلا الشيء أعم، ولكن فقط من خلال جعلها أكثر تعقيدا أيضا:)

وأنت لا يمكن عن طريق الوراثة الاختيار إذا كان نوع من "اليسار" هو نفسه كنوع من "حق" في وقت التشغيل. ويتم تنفيذ الوراثة جافا عبر نوع محو ، بحيث يتم فقدان المعلومات حول المعلمات نوع عام في وقت التشغيل.

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top