type information - Using Class Literals

本文介绍了如何使用类字面量重实现PetCreator,这种方法在很多方面使代码更简洁。通过在OnJava8-Examples目录下运行PetCount2,并对比输出结果,可以展示类字面量的优势。

previous article

If we reimplement PetCreator using lcass literals, the result is cleaner in many ways:

// typeinfo/pets/LiteralPetCreator.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Using class literals
// {java typeinfo.pets.LiteralPetCreator}
package typeinfo.pets;

import java.util.*;

public class LiteralPetCreator extends PetCreator {
  // No try block needed.
  @SuppressWarnings("unchecked")
  public static final List<Class<? extends Pet>> ALL_TYPES =
      Collections.unmodifiableList(
          Arrays.asList(
              Pet.class,
              Dog.class,
              Cat.class,
              Rodent.class,
              Mutt.class,
              Pug.class,
              EgyptianMau.class,
              Manx.class,
              Cymric.class,
              Rat.class,
              Mouse.class,
              Hamster.class));
  // Types for random creation:
  private static final List<Class<? extends Pet>> TYPES =
      ALL_TYPES.subList(ALL_TYPES.indexOf(Cat.class), ALL_TYPES.size());

  @Override
  public List<Class<? extends Pet>> types() {
    return TYPES;
  }

  public static void main(String[] args) {
    System.out.println(TYPES);
  }
}
/* Output:
[class typeinfo.pets.Cat, class typeinfo.pets.Rodent, class typeinfo.pets.Mutt, class typeinfo.pets.Pug, class typeinfo.pets.EgyptianMau, class typeinfo.pets.Manx
, class typeinfo.pets.Cymric, class typeinfo.pets.Rat, class typeinfo.pets.Mouse, class typeinfo.pets.Hamster]
*/

run it by in OnJava8-Examples directory:

% javac typeinfo/pets/LiteralPetCreator.java
% java typeinfo.pets.LiteralPetCreator
/**
     * Returns an unmodifiable view of the specified list.  This method allows
     * modules to provide users with "read-only" access to internal
     * lists.  Query operations on the returned list "read through" to the
     * specified list, and attempts to modify the returned list, whether
     * direct or via its iterator, result in an
     * <tt>UnsupportedOperationException</tt>.<p>
     *
     * The returned list will be serializable if the specified list
     * is serializable. Similarly, the returned list will implement
     * {@link RandomAccess} if the specified list does.
     *
     * @param  <T> the class of the objects in the list
     * @param  list the list for which an unmodifiable view is to be returned.
     * @return an unmodifiable view of the specified list.
     */
    public static <T> List<T> unmodifiableList(List<? extends T> list) {
        return (list instanceof RandomAccess ?
                new UnmodifiableRandomAccessList<>(list) :
                new UnmodifiableList<>(list));
    }
// typeinfo/pets/Pets.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Facade to produce a default PetCreator
package typeinfo.pets;
import java.util.*;
import java.util.stream.*;

public class Pets {
  public static final PetCreator CREATOR =
    new LiteralPetCreator();
  public static Pet get() {
    return CREATOR.get();
  }
  public static Pet[] array(int size) {
    Pet[] result = new Pet[size];
    for(int i = 0; i < size; i++)
      result[i] = CREATOR.get();
    return result;
  }
  public static List<Pet> list(int size) {
    List<Pet> result = new ArrayList<>();
    Collections.addAll(result, array(size));
    return result;
  }
  public static Stream<Pet> stream() {
    return Stream.generate(CREATOR);
  }
}
// typeinfo/PetCount2.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import typeinfo.pets.*;

public class PetCount2 {
  public static void main(String[] args) {
    PetCount.countPets(Pets.CREATOR);
  }
}
/* Output:
Mouse Manx Pug Rodent Rodent Hamster Mouse Cat Mutt Rat Mouse Mouse Rodent Hamster Hamster Mouse Mouse Rodent Cat Mouse
{Pug=1, Mouse=7, Rat=1, Cat=3, Manx=1, Rodent=15, Mutt=1, Dog=2, Pet=20, Hamster=3}
*/

run PetCount2 please use 

./gradlew  :typeinfo:PetCount2

and use 

./gradlew  :typeinfo:PetCount

compare the output results.

next article

refrences:

1. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/pets/LiteralPetCreator.java

2. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/pets/PetCount.java

4. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/pets/PetCount2.java

Lab 2 Chapter 1 Java Language Programming Chapter 1: Variables and Primitive Data Types (Part 2) Instructor: Ahsan Shehzad Date: September 3, 2025 Practical Session Objective Lab Goal: Store and Display a Contact Our objective is to create a simple Java program that stores the information for one contact using variables and then prints that information neatly to the console. Final Result Preview: (This is what your console output will look like) (Screenshot of the final console output will go here) Prerequisites: Java Development Kit (JDK) 11 or higher installed. An IDE like IntelliJ IDEA Community Edition ready to go. Step-by-Step Guided Exercise Step 1: Create the Project Structure Goal: Set up your project in IntelliJ and create the main class file. Instructions: 1. Open IntelliJ IDEA. 2. Go to File > New > Project... . 3. Name your project MyContactManager and choose a location to save it. Contact Profile: Name: John Doe Age: 32 Phone: 447700900123 Is a Friend: true 1 2 3 4 54. Ensure Java is selected and you have a JDK configured. 5. Once the project is created, right-click the src folder in the Project Explorer. 6. Select New > Java Class . 7. Name the class Main and press Enter. Code Block: Your IDE will generate this boilerplate code for you. Add the main method inside the class. Expected Result: You have a clean Main.java file, and the program can be run (though it won't do anything yet). Step 2: Declare and Initialize Contact Variables Goal: Create variables inside the main method to hold a contact's data. Instructions: 1. Inside the main method, declare and initialize variables for each piece of contact information. 2. Choose the most appropriate data type for each value. 3. Pay special attention to the literals for long ( L ) and String (double quotes). Code Block: Add the following lines inside your main method. Expected Result: The program should compile without any errors. When you run it, still nothing will happen, but the data is now stored in memory. public class Main { public static void main(String[] args) { // Our code will go here! } } 1 2 3 4 5 public static void main(String[] args) { // String is a special object type we use for text. String firstName = "John"; String lastName = "Doe"; // Use 'int' for age. int age = 32; // A phone number can be large, so 'long' is a safe choice. long phoneNumber = 447700900123L; // 'boolean' is perfect for a simple true/false status. boolean isFriend = true; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14Step 3: Display the Information Goal: Use System.out.println() and string concatenation ( + ) to print the stored data to the console. Instructions: 1. After the variable declarations, add a println statement to act as a header. 2. For each variable, write a println that combines a descriptive label (e.g., "Name: ") with the variable itself using the + operator. Code Block: Add these lines after your variables in the main method. Expected Result: When you run the main method, you should see the formatted contact details printed to your console, matching the goal on slide 13. Putting It All Together Goal: Review the complete, final code for this lab session. Instructions: Your final Main.java file should look exactly like this. Make sure your code matches and run it one last time to confirm the output. Code Block: // ... variables from previous slide ... // --- Displaying the Information --- System.out.println("Contact Profile:"); System.out.println("Name: " + firstName + " " + lastName); System.out.println("Age: " + age); System.out.println("Phone: " + phoneNumber); System.out.println("Is a Friend: " + isFriend); 1 2 3 4 5 6 7 8 public class Main { public static void main(String[] args) { // --- Storing Contact Information --- // String is a special object type we use for text. String firstName = "John"; String lastName = "Doe"; // Use 'int' for age. int age = 32; // A phone number can be large, so 'long' is a safe choice. long phoneNumber = 447700900123L; // 'boolean' is perfect for a simple true/false status. boolean isFriend = true; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16Expected Result: A clean, working program that successfully stores and displays data. You've just completed Phase 1 of the project! (This slide is intentionally left blank to fit the 21-slide structure. It can be used for instructor-specific notes or an extra exercise if needed.) Challenge Task For Those Who Finish Early... Challenge 1: Add a Second Contact Declare and initialize a new set of variables for a second person (e.g., firstName2 , age2 , etc.). Print their details to the console, separated from the first contact by a line of dashes ( "----------" ). Challenge 2: Perform a Calculation After creating both contacts, declare a new double variable named averageAge . Calculate the average age of the two contacts and store it in the variable. Hint: (age1 + age2) / 2.0 . Why / 2.0 and not / 2 ? Print the average age to the console with a descriptive label. // --- Displaying the Information --- System.out.println("Contact Profile:"); System.out.println("Name: " + firstName + " " + lastName); System.out.println("Age: " + age); System.out.println("Phone: " + phoneNumber); System.out.println("Is a Friend: " + isFriend); } } 17 18 19 20 21 22 23 24 答案是什么
09-22
MATLAB主动噪声和振动控制算法——对较大的次级路径变化具有鲁棒性内容概要:本文主要介绍了一种在MATLAB环境下实现的主动噪声和振动控制算法,该算法针对较大的次级路径变化具有较强的鲁棒性。文中详细阐述了算法的设计原理与实现方法,重点解决了传统控制系统中因次级路径动态变化导致性能下降的问题。通过引入自适应机制和鲁棒控制策略,提升了系统在复杂环境下的稳定性和控制精度,适用于需要高精度噪声与振动抑制的实际工程场景。此外,文档还列举了多个MATLAB仿真实例及相关科研技术服务内容,涵盖信号处理、智能优化、机器学习等多个交叉领域。; 适合人群:具备一定MATLAB编程基础和控制系统理论知识的科研人员及工程技术人员,尤其适合从事噪声与振动控制、信号处理、自动化等相关领域的研究生和工程师。; 使用场景及目标:①应用于汽车、航空航天、精密仪器等对噪声和振动敏感的工业领域;②用于提升现有主动控制系统对参数变化的适应能力;③为相关科研项目提供算法验证与仿真平台支持; 阅读建议:建议读者结合提供的MATLAB代码进行仿真实验,深入理解算法在不同次级路径条件下的响应特性,并可通过调整控制参数进一步探究其鲁棒性边界。同时可参考文档中列出的相关技术案例拓展应用场景。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值